Laravel 4 Query eloquente usando WHERE con OR AND OR?

Come faccio a dire WHERE (a = 1 OR b =1 ) AND (c = 1 OR d = 1)

Per le query più complicate dovrei usare l'SQL grezzo?

Soluzione

Fai uso di Parameter Grouping (Laravel 4.2). Per il tuo esempio, sarebbe qualcosa del genere:

Model::where(function ($query) {
    $query->where('a', '=', 1)
          ->orWhere('b', '=', 1);
})->where(function ($query) {
    $query->where('c', '=', 1)
          ->orWhere('d', '=', 1);
});
Commentari (2)

Se vuoi usare i parametri per a,b,c,d in Laravel 4

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);
});
Commentari (0)

Nel caso in cui tu stia mettendo in loop le condizioni OR, non hai bisogno del secondo $query->where degli altri post (in realtà non credo che tu abbia bisogno in generale, puoi semplicemente usare orWhere nel where annidato se più facile)

$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);
    }
});
Commentari (1)