我怎么说WHERE (a =1 OR b =1) AND (c =1 OR d =1)

对于更复杂的查询,我应该使用原始SQL吗?


当前回答

如果你循环OR条件,你不需要第二个$查询->where来自其他帖子(实际上我不认为你一般需要,你可以在嵌套的where中使用orWhere如果更容易)

$attributes = ['first'=>'a','second'=>'b'];

$query->where(function ($query) use ($attributes) 
{
    foreach ($attributes as $key=>value)
    {
        //you can use orWhere the first time, doesn't need to be ->where
        $query->orWhere($key,$value);
    }
});

其他回答

在Laravel Eloquent中简单使用:

$a='foo', $b='bar', $c='john', $d='doe';

Coder::where(function ($query) use ($a, $b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
})->get();

将产生如下查询:

SELECT * FROM <table> WHERE (a='foo' or b='bar') AND (c='john' or d='doe');

如果你循环OR条件,你不需要第二个$查询->where来自其他帖子(实际上我不认为你一般需要,你可以在嵌套的where中使用orWhere如果更容易)

$attributes = ['first'=>'a','second'=>'b'];

$query->where(function ($query) use ($attributes) 
{
    foreach ($attributes as $key=>value)
    {
        //you can use orWhere the first time, doesn't need to be ->where
        $query->orWhere($key,$value);
    }
});

你也可以使用查询作用域来让事情变得更整洁,所以你可以这样做:

Invoice::where('account', 27)->notPaidAt($date)->get();

然后在你的模型中

public function scopeNotPaidAt($query, $asAt)
{
    $query = $query->where(function ($query) use ($asAt) { 
        $query->where('paid', '=', '0000-00-00')->orWhere('paid', '>=', $asAt); 
    });
    return $query;    
}

对于雄辩的查询构建器,以下查询将不起作用:

MODELNAME::where('a', 1)->orWhere('b', 1)->where('c', 1)->orWhere('d', 1);

但是你可以使用下面的代码:

MODELNAME::where(function($a) {
    $a->where('a', 1)->orWhere('b', 1);
})->where(function($a) {
    $a->where('c', 1)->orWhere('d', 1);
});

您可以使用第二个查询,它将完美地工作。

这对我很有用

$business = Model::where('model_id', $model_id1)->orWhere('model_id', $model_id2)->first();