Laravel whereHas on multiple relationships

后端 未结 3 1533
庸人自扰
庸人自扰 2020-12-25 15:45

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 (relate

相关标签:
3条回答
  • 2020-12-25 15:49

    Yes that's possible.

    The generated SQL will probably be:

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

    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' );
            });
        });
    
    0 讨论(0)
  • 2020-12-25 16:00

    I don't think you need 'with' as there is 'wherehas'

    Model::whereHas('territory',function( $query ){
            $query->where('region','Australia');
        })->whereHas('homeClub', function ( $query ) {
            $query->where('name', 'Arsenal' );
        })->orWhereHas('awayClub', function ( $query ) {
            $query->where('name', 'Arsenal' );
        });
    
    0 讨论(0)
  • 2020-12-25 16:14

    Thanks to being shown in the right direction by edi9999 - I wasn't properly considering parameter grouping

    use the main eloquent object in the anonymous function, I placed a whereHas and an orWhereHas constraint on the homeClub and awayClub and that did the trick.

    $ret->with('territory')->with('homeClub')->with('awayClub')->with('programme');
    
        $ret
            ->whereHas('territory',function( $query ) use ( $parameterValues ){
                $query->where('region', $parameterValues['region_names'] );
            })
            ->whereHas('season', function ( $query ) use ( $parameterValues ){
                $query->where('name', $parameterValues['season_names'] );
            })
            ->where( function( $subquery ) use ( $ret ){
                $ret->whereHas('homeClub', function ( $query ){
                    $query->where('name','Arsenal' );
                } );
                $ret->orWhereHas('awayClub', function ( $query ){
                    $query->where('name','Arsenal');
                 });
            });
    
    0 讨论(0)
提交回复
热议问题