我有一个原始查询,如下所示:
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 = ...;
这不是正确的查询,我该如何解决?
答案 0 :(得分: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 :(得分: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();