Laravel有多重关系 [英] Laravel whereHas on multiple relationships

查看:141
本文介绍了Laravel有多重关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否可以对多种关系执行此新功能吗?

Does anyone know if this new feature can be performed on multiple relationships?

例如,我有一个查询,不仅要过滤俱乐部名称(

For example, I have a query where I want to filter on not only the club name (related question) but also the territory name.

在此示例中,我想要查询俱乐部(俱乐部关系)名称为阿森纳,地区为澳大利亚(领土关系)的查询结果

In this example, I'd like query results where the club (club relationship) name is Arsenal and the the region is Australia (territory relationship)

$ret->with('territory')->with('homeClub')->with('awayClub');
    $ret->whereHas('territory',function( $query ){
            $query->where('region','Australia');
        })->whereHas('homeClub', function ( $query ) {
            $query->where('name', 'Arsenal' );
        })->orWhereHas('awayClub', function ( $query ) {
            $query->where('name', 'Arsenal' );
        });

执行此查询时-结果不会限制区域whereHas只是俱乐部.

When executing this query - the result isn't constraining the territory whereHas just the clubs one.

可以链接到何处以过滤先前关系的何处的结果吗?有没有建议?

Can whereHas be chained to filter the results on previous relationship's whereHas? Any suggestions if not?

谢谢

乔恩

推荐答案

是的.

生成的SQL可能是:

SELECT * FROM ... WHERE (territory constraint) AND (homeClub constratint) OR (awayClub constraint)

这意味着如果满足awayClub constraint,将检索该行.我想您想在生成的sql中添加括号:

This means that if awayClub constraint is satisfied, the line will be retrieved. I think you want to add a parenthesis to the generated sql:

SELECT * FROM ... WHERE (territory constraint) AND ((homeClub constratint) OR (awayClub constraint))

要这样做,您需要将两个查询嵌套在一个地方:

to do that, you need to nest both queries inside a where:

$ret->with('territory')->with('homeClub')->with('awayClub');
    $ret->whereHas('territory',function( $query ){
        $query->where('region','Australia');
    })
    ->where(function($subQuery)
    {   
        $subQuery->whereHas('homeClub', function ( $query ) {
            $query->where('name', 'Arsenal' );
        })
        ->orWhereHas('awayClub', function ( $query ) {
            $query->where('name', 'Arsenal' );
        });
    });

这篇关于Laravel有多重关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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