laravel WhereHas() / orWhereHas 没有按预期约束查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21116742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:43:04  来源:igfitidea点击:

WhereHas() / orWhereHas not constraining the query as expected

laravellaravel-4

提问by HowApped

I am using the new whereHas method to add a constraint on an eager loaded relationship in Laravel 4.1.

我正在使用新的 whereHas 方法在 Laravel 4.1 中添加对急切加载关系的约束。

$broadcast = $broadcast->whereHas('season', function( $query ) use ( $parameterValues ){
              $query->where('name', '2011-12' );
          });
      }

In this example, I'm searching for a football/soccer broadcast where the relationship is that a broadcast belongsToa Season

在这个例子中,我正在搜索一个足球/足球广播,其中的关系是belongsTo一个赛季的广播

I want to add a constraint for team (club) where the relationship is that a Broadcast hasOnehomeClub and a broadcast hasOneawayClub. I want results for where a team (liverpool) is either the home or the away club so I try to use the orWhereHas- a featured added in L4.1

我想为团队(俱乐部)添加一个约束,其中关系是一个广播hasOnehomeClub 和一个广播hasOne客场俱乐部。我想要球队(利物浦)是主场还是客场俱乐部的结果,所以我尝试使用orWhereHas-在 L4.1 中添加的功能

        $broadcast = $broadcast->with('homeClub')->whereHas('homeClub', function( $query ) use ( $parameterValues ){
              $query->where('abb', $parameterValues['club_abbs'] );
          });
          $broadcast = $broadcast->with('awayClub')->orWhereHas('awayClub', function( $query ) use ( $parameterValues ){
              $query->where('abb', $parameterValues['club_abbs'] );
          });

But this just seems to cancel out the constraint on the season that's mentioned in my first example. It's like, by chaining the the orWhereHas, my wheremethods have 'forgotten' what they were constraining.

但这似乎抵消了我在第一个例子中提到的对赛季的限制。就像,通过链接 orWhereHas,我的where方法已经“忘记”了它们所限制的内容。

Any help, greatly appreciated - thanks

任何帮助,非常感谢 - 谢谢

Jon.

乔恩。

回答by HowApped

I was using the method incorrectly. I loaded both associations first and then chained the whereHasand orWhereHas

我错误地使用了该方法。我先加载了两个关联,然后链接了whereHasorWhereHas

$broadcast = $broadcast->with('homeClub');
$broadcast = $broadcast->with('awayClub');


    $broadcast = $broadcast->whereHas('homeClub', function( $query ) use ( $parameterValues ){
      $query->where('abb', 'liverpool' );
  })->orWhereHas('awayClub', function( $query ) use ( $parameterValues ){
      $query->where('abb', 'liverpool' );
  });