laravel Eloquent where 条件基于“属于”关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23970762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:50:05  来源:igfitidea点击:

Eloquent where condition based on a "belongs to" relationship

laravelwhereeloquentbelongs-to

提问by Lior

Let's say I have the following model:

假设我有以下模型:

class Movie extends Eloquent
{
    public function director()
    {
        return $this->belongsTo('Director');
    }
}

Now I'd like fetch movies using a where condition that's based on a column from the directors table.

现在我想使用基于导演表中一列的 where 条件来获取电影。

Is there a way to achieve this? Couldn't find any documentation on conditions based on a belongs to relationship.

有没有办法实现这一目标?找不到任何关于基于属于关系的条件的文档。

回答by The Alpha

You may try this (Check Querying Relationson Laravelwebsite):

你可以试试这个(检查网站上的查询关系Laravel):

$movies = Movie::whereHas('director', function($q) {
    $q->where('name', 'great');
})->get();

Also if you reverse the query like:

此外,如果您反转查询,如:

$directorsWithMovies = Director::with('movies')->where('name', 'great')->get();
// Access the movies collection
$movies = $directorsWithMovies->movies;

For this you need to declare a hasmanyrelationship in your Directormodel:

为此,您需要hasmanyDirector模型中声明一个关系:

public function movies()
{
    return $this->hasMany('Movie');
}