Laravel 属于通过类似关系

Fau*_*kus 6 php relationship laravel

现在我有这些方法:

程序.php

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

用户.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;
}
Run Code Online (Sandbox Code Playgroud)

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

因为现在我将程序放入集合中,然后从数据库中获取机构,并在此过程中建立松散的关系。

想要类似的东西:

public function institute()
{
    return $this->programmes()->first()->institute();
}
Run Code Online (Sandbox Code Playgroud)

Siv*_*jan 8

一种倒置的“直通关系”会起作用。

如果我们有

图书馆 -> 作者 -> 书籍

像关系那么下面的代码将起作用(假设Author表有library_id并且Book表有author_id作为外键)

public function library()
{
    return $this->hasOneThrough(Library::class,Author::class,
                                'id','id','author_id','library_id');
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ris 5

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

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

User::with('programmes.institute')->find($id);
Run Code Online (Sandbox Code Playgroud)

如果您尝试在用户和机构之间建立关系,您可能需要执行以下操作:

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

您可以在此处阅读有关多对多关系的文档。

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