How can I add a model into the relations array of another model?

例如.

  • 域名属于所有者.
  • 所有者只有一个域名.
  • 我有$domain(Domain的实例).
  • 我有$Owner(Owner的实例).

我想把$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.

那么为了可读性,我想用$owner->domain->id等.

$domain->owner()->associate($owner); gives me a $domain->owner option

But then I can't work out the opposite version

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

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

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

NB: I don't want to save anything as I've already loaded all the data i need.

推荐答案

setRelation() should work. It just sets the value in the relations array.

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

Laravel相关问答推荐

Laravel 联合和分页

使用 fetch api 时 Laravel 控制器不存在错误

当使用Laravel eloquent查询100000条数据时速度很慢

在 laravel 4.2 中,用户 'root'@'localhost' 的 Laravel 访问被拒绝(使用密码:YES)

Laravel 5.1 - 如何在进度条上设置消息

Laravel 5表单请求验证返回禁止错误

如何处理 Laravel 的 SMTP 驱动程序中的自签名 TLS 证书?

Eager加载:在具有eloquent关系的枢轴上使用`with`

路由模型绑定不起作用

错误:您的要求无法解析为一组可安装的软件包.

加载模型的所有关系

Laravel 4 上传图片表单

Laravel5如何将数组传递给查看

Laravel 4:将什么作为参数传递给 Url 类?

日期时间格式无效:1366 字符串值不正确

如何在特定项目中禁用初始化 JS/TS 语言功能?

在laravel中删除确认

同一模型上的 Laravel 父/子关系

在 Laravel 中软删除父记录时如何软删除相关记录?

限制自己重载外部 API 的速率