【问题标题】:Laravel belongsToThrough like relationshipLaravel belongsToThrough 类似的关系
【发布时间】:2018-11-25 05:15:20
【问题描述】:

现在我有这些方法:

程序.php

public function institute()
{
    return $this->belongsTo(Institute::class, 'institute_id')->withTrashed();
}

用户.php

public function programmes()
{
    // These programmes belongs to the same institute
    return $this->belongsToMany(Programme::class);
}

public function getInstituteAttribute()
{
    return $this->programmes->first()->institute ?? null;
}

如何通过一个 SQL 查询获取机构并保持关系?

因为现在我将程序提取到集合中,然后我从 DB 中提取机构,并且沿途关系松散。

想要类似的东西:

public function institute()
{
    return $this->programmes()->first()->institute();
}

【问题讨论】:

  • 提供更多信息
  • @MadhuNair 给你

标签: php laravel relationship


【解决方案1】:

您可以预先加载嵌套关系,您可以在the the documentation 中查看有关它们的更多信息。

要急切加载嵌套关系,您可以使用“点”语法:

User::with('programmes.institute')->find($id);

如果您试图在用户和机构之间建立关系,您可能会希望这样做:

public function institutes()
{
    return $this->belongsToMany(Institute::class, 'programmes', 'user_id', 'institute_id');
}

您可以在此处阅读有关多对多关系的documentation

除了自定义连接表的名称外,您还可以 通过传递自定义表上键的列名 belongsToMany 方法的附加参数。第三个论据 是您要在其上定义的模型的外键名称 关系,而第四个参数是外键名 您要加入的模型

【讨论】:

  • 是的,但这不是我要寻找的:(
  • 你在搜索什么?
  • 想谈恋爱
  • 您能否将三个表的架构添加到您的问题中?
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 2014-10-25
  • 2020-04-05
  • 2018-09-27
  • 2017-02-06
  • 2015-03-15
  • 2015-05-29
  • 1970-01-01
相关资源
最近更新 更多