使用 Eloquent 手动注入模型关系

Manually inject model relation using Eloquent

如何将一个模型添加到另一个模型的关系数组中?

例如

我想将 $domain 添加到 $owner->relations[] 以便我稍后可以在我的代码中使用 $owner->domain

这样做的原因是,在一个特定的控制器中,我只需要来自每个模型的部分数据集,因此出于性能原因使用 fluent 来查询连接,然后填充模型。

那么为了便于阅读,我想使用 $owner->domain->id

$domain->owner()->associate($owner); 给我一个 $domain->owner 选项

但是后来我想不出相反的版本

$owner->domain()->associate($domain)
$owner->domain()->attach($domain)

两者都会导致以下致命错误

Call to undefined method Illuminate\Database\Query\Builder::[attach|associate] ()

注意:我不想保存任何东西,因为我已经加载了我需要的所有数据。

setRelation() should work. It sets the value in the relations数组。

$owner->setRelation('domain', $domain);

设置一对多关系时,可能需要使用values():

$owner->setRelation('domains', $domains->values());