雄辩基于"属于"关系的条件

Lio*_*ior 23 where belongs-to laravel eloquent

假设我有以下型号:

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

现在我想使用基于director表中的列的where条件来获取电影.

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

The*_*pha 43

您可以尝试这个(在网站上查询查询关系Laravel):

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

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

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

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

public function movies()
{
    return $this->hasMany('Movie');
}
Run Code Online (Sandbox Code Playgroud)

  • `function($ q)use($ variable){// $ variable}` (3认同)
  • 第一个实际上有效!我什至没有尝试过,因为那里没有关系,只有一个belongsTo。仍然不确定为什么会起作用,以及为什么没有whereBelongsTo条件。 (2认同)

mar*_*e96 5

属于哪里()

对于新版本的 Laravel,您可以使用whereBelongsTo().

它看起来像这样:

$director = Director::find(1);
$movies = Movie::whereBelongsTo($director);
Run Code Online (Sandbox Code Playgroud)

更多内容请参阅文档

是()

对于一对一关系is()可以使用。

$director = Director::find(1);
$movie = Movie::find(1);

$movie->director()->is($director);
Run Code Online (Sandbox Code Playgroud)