口述其中基于“属于”的条件关系 [英] Eloquent where condition based on a "belongs to" relationship

查看:171
本文介绍了口述其中基于“属于”的条件关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下模型:

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

现在我想使用一个条件这是基于董事会表中的一列。



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

解决方案

您可以尝试这个(检查 Laravel 网站上的https://laravel.com/docs/5.3/eloquent-relationships#querying-relations =noreferrer>查询关系) :

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

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

  $ directorWithMovies = Director :: with('movies') - > where('name','great') - > get(); 
//访问电影集
$ movies = $ DirectorsWithMovies->电影;

为此,您需要声明一个 hasmany 关系在您的导演模型:

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


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.

解决方案

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

这篇关于口述其中基于“属于”的条件关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆