Laravel Eloquent - 如何组织条件

时间:2018-04-25 10:28:21

标签: php laravel eloquent

我使用以下雄辩声明

Title::where('word', 'lovers')->orWhere('word', 'lover')->where('domain', $resultFromFirstKeyword->domain)->get();

我可以通过SQL记录器看到它产生以下SQL

select * from `title` where `word` = 'lovers' or `word` = 'lover' and `domain` = 'www.texasbirdlovers.com'

但是我想要生成的SQL是

select * from `title` where (`word` = 'lovers' or `word` = 'lover') and `domain` = 'www.texasbirdlovers.com'

我将如何实现这一目标?

4 个答案:

答案 0 :(得分:4)

这应该有效:

Title::whereIn('word', ['lovers', 'lover'])
    ->where('domain', $resultFromFirstKeyword->domain)
    ->get();

但是,如果你想要像你说的那样组合它们,试试这个:

Title::where(function($query) {
        $query->where('word', 'lovers')
            ->orWhere('word', 'lover');
    })
    ->where('domain', $resultFromFirstKeyword->domain)
    ->get();

答案 1 :(得分:1)

group子句

中只需where您的查询
Title::where(function($q){
         $q->where('word', 'lovers')->orWhere('word', 'lover');
 })->where('domain', $resultFromFirstKeyword->domain)->get();

答案 2 :(得分:1)

尝试

Title::->where('domain', $resultFromFirstKeyword->domain)
    ->where(function($query)
        {
            $query->where('word','=',lovers)
            ->orWhere('word','=','word');
        })->get();

答案 3 :(得分:1)

尝试以下方法:

Title::where(function( $query ) {
     $query->where( 'word', 'lover' )
     ->orWhere( 'word', 'lovers' )
})->
->where( 'domain', $resultFromFirstKeyword->domain )
->get();