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

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


当前回答

这对我很有用

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

其他回答

如果你想在Laravel 4中使用a,b,c,d的参数

Model::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);
});

如果你循环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);
    }
});

您还可以查询第一个或条件,然后可以应用另一个或条件

$model = Model::where('a',1)->orWhere('b',1);

现在对$model变量应用另一个条件

$model1 = $model->where('c',1)->orWhere('d',1)->get();

另一种不使用Modal的方法

数据库:股票 列:id、名称、company_name exchange_name,地位

  $name ='aa'
  $stocks = DB::table('stocks')
            ->select('name', 'company_name', 'exchange_name')
            ->where(function($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%')
                ->orWhere('company_name', 'like', '%' . $name . '%');
            })
            ->Where('status', '=', 1)
            ->limit(20)
            ->get();

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

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;    
}