Eloquent where condition based on a “belongs to” relationship

我与影子孤独终老i 提交于 2019-12-31 08:59:34

问题


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:


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');
}


来源:https://stackoverflow.com/questions/23970762/eloquent-where-condition-based-on-a-belongs-to-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!