2017-03-27 18 views
0

を通じて、このクエリを実行することができ、私はこのようになります生のクエリを持っています。どのように私は雄弁

SELECT sum(count) AS f FROM transactions WHERE userid = :userid AND 
((date = :date_1 AND month = :month_1 and YEAR = :year_1) OR 
(date = :date_2 AND month = :month_2 and YEAR = :year_2) OR 
... 
... 
... 
(date = :date_n AND month = :month_n and YEAR = :year_n); 

日付関連のパラメータは、次のような日付を含む配列、(の長さに依存配列は変わる可能性があります)。

[ 
    ['d' => 10, 'm' => 12, 'y' => 1994], 
    ['d' => 30, 'm' => 1, 'y' => 2003] 
    // ... 
] 

私は同等のEloquent文を思い付くことができません。私がしようとした場合:

$tr_query = Transactions::select(DB::raw('sum(count) as f')); 

foreach ($dates as $date) { 
    $tr_query->orWhere([ 
    'date' => $date['d'], 
    'month' => $date['m'], 
    'year' => $year['y'] 
    ]); 
} 

$tr_query->where('userid', $userid); 

を内部的には、これは、その結果:

SELECT sum(count) AS f FROM transactions WHERE 
(date = ... and month = ... and year = ...) OR 
(date = ... and month = ... and year = ...) OR 
... 
(date = ... and month = ... and year = ...) AND 
userid = ...; 

これは正しいクエリではありませんので、私はそれをどのように修正することができますか?

答えて

1

問題は、あなたが次の操作を行うことができ、ネストされた場合:

$tr_query = Transactions::select(DB::raw('sum(count) as f')); 


$tr_query->where('userid', $userid); 
$tr_query->where(function ($query) use ($dates) { 
    foreach ($dates as $date) { 
    $query->orWhere([ 
     'date' => $date['d'], 
     'month' => $date['m'], 
     'year' => $year['y'] 
    ]); 
    } 
}); 
1

あなたはthe where() closureを使用する必要があります。

$tr_query = Transactions::select(DB::raw('sum(count) as f')) 
    ->where('userid', $userid); 
    ->where(function($q) use($dates) { 
     foreach ($dates as $date) { 
      $q->orWhere([ 
       'date' => $date['d'], 
       'month' => $date['m'], 
       'year' => $year['y'] 
      ]); 
     } 
    })->get();