Php 拉雷维尔·贝朗斯托式关系

Php 拉雷维尔·贝朗斯托式关系,php,laravel,relationship,Php,Laravel,Relationship,现在我有了这些方法: Program.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

现在我有了这些方法:

Program.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查询获取institute并保持关系

因为现在我把程序收集起来,然后我从数据库中取出研究所,一路上关系松散

我想要一些类似于:

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

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

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

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

public function institutes()
{
    return $this->belongsToMany(Institute::class, 'programmes', 'user_id', 'institute_id');
}
您可以在这里阅读有关多对多关系的

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


再倒一些information@MadhuNair这是你的答案,但这不是我要搜索的:(你在搜索什么?想建立一个关系吗?你能在你的问题中添加三个表的模式吗?
public function institutes()
{
    return $this->belongsToMany(Institute::class, 'programmes', 'user_id', 'institute_id');
}