如何仅使用模型实例构建Laravel关系



我正在使用文件导入数据。导入不会创建一组单个模型,而是创建一组复杂的相关模型。我想向用户展示,如果他们导入数据集而不在数据库中实际存储任何内容,会发生什么。我想把模型实例发送到我的视图中,就好像它是导入的一样。

我可以为模型建立完整的属性集并用这些属性实例化模型(new Model($attributes)(,但我也可以";负载";手动与另一个模型实例建立关系?

$parent = new Parent($parentAttributes);
$related = new Related($relatedAttributes);
// Add $related to a $parent relationship so that I can access it from $parent somehow
dump($parent->related);
// This would output the same model as $related

似乎IlluminateDatabaseEloquentConcernsHasRelationships有一个名为setRelation的函数可以提供此功能。

$parent = new Parent($parentAttributes);
$related = new Related($relatedAttributes);
$parent->setRelation('related', $related);
assertEquals($related, $parent->related); // true

这实际上允许您设置任意的";关系";而不是基于实际定义数据库关系(例如具有在模型上定义的related()关系(。它使用与您在setRelation中使用的密钥相匹配的魔术属性。

$parent = new Parent();
$model = new Model();
$parent->setRelation('arbitraryKey', $model);
assertEquals($model, $parent->arbitraryKey); // true

最新更新