现在我有这些方法:
程序.php
public function institute()
{
return $this->belongsTo(Institute::class, 'institute_id')->withTrashed();
}
User.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 查询获取机构并保持关系?
因为现在我将程序放入集合中,然后从数据库中获取机构,并在此过程中建立松散的关系。
想要类似的东西:
public function institute()
{
return $this->programmes()->first()->institute();
}
您可以预先加载嵌套关系,您可以在以下位置查看有关它们的更多信息文档 https://laravel.com/docs/5.6/eloquent-relationships#eager-loading.
要预先加载嵌套关系,您可以使用“点”语法:
User::with('programmes.institute')->find($id);
如果您尝试在用户和机构之间建立关系,您可能需要执行以下操作:
public function institutes()
{
return $this->belongsToMany(Institute::class, 'programmes', 'user_id', 'institute_id');
}
您可以在这里阅读有关文档 https://laravel.com/docs/5.6/eloquent-relationships#updating-belongs-to-relationships对于多对多关系。
除了自定义连接表的名称之外,您还可以
通过传递自定义表上键的列名称
belongsToMany 方法的附加参数。第三个论点
是您定义的模型的外键名称
关系,而第四个参数是外键名称
您要加入的模型
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)