Eloquent where condition based on a “belongs to” r

2019-03-09 19:04发布

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.

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

1条回答
疯言疯语
2楼-- · 2019-03-09 20:03

You may try this (Check Querying Relations on Laravel website):

$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 hasmany relationship in your Director model:

public function movies()
{
    return $this->hasMany('Movie');
}
查看更多
登录 后发表回答