laravel 使用 Eloquent 手动注入模型关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31288938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manually inject model relation using Eloquent
提问by Ben Swinburne
How can I add a model into the relations array of another model?
如何将模型添加到另一个模型的关系数组中?
E.g.
例如
- Domain belongsTo Owner.
- Owner hasOne Domain.
- I have $domain (instance of Domain).
- I have $owner (instance of Owner).
- 域属于所有者。
- 所有者有一个域。
- 我有 $domain(域的实例)。
- 我有 $owner (所有者的实例)。
I want to add $domain
to $owner->relations[]
so that I can just use $owner->domain
later on in my code.
我想添加$domain
到$owner->relations[]
以便$owner->domain
稍后在我的代码中使用。
The reason for doing this is such that in one particular controller i only need a partial data set from each model so use fluent to query with a join for performance reasons then fill the models.
这样做的原因是,在一个特定的控制器中,我只需要来自每个模型的部分数据集,因此出于性能原因使用 fluent 查询连接,然后填充模型。
Then for readability's sake I'd like to use $owner->domain->id
etc
然后为了可读性,我想使用$owner->domain->id
etc
$domain->owner()->associate($owner);
gives me a $domain->owner
option
$domain->owner()->associate($owner);
给我一个$domain->owner
选择
But then I can't work out the opposite version
但后来我无法计算出相反的版本
$owner->domain()->associate($domain)
$owner->domain()->attach($domain)
both result in the following fatal error
两者都会导致以下致命错误
Call to undefined method Illuminate\Database\Query\Builder::[attach|associate] ()
调用未定义的方法 Illuminate\Database\Query\Builder::[attach|associate] ()
NB: I don't want to save anything as I've already loaded all the data i need.
注意:我不想保存任何东西,因为我已经加载了我需要的所有数据。
回答by lukasgeiter
setRelation()
should work. It just sets the value in the relations
array.
setRelation()
应该管用。它只是设置relations
数组中的值。
$owner->setRelation('domain', $domain);