[英]SQL query in Laravel Eloquent Query
How to produce query like below in laravel eloquent 如何在laravel雄辩中产生如下所示的查询
SELECT *
FROM TABLE
WHERE column1=value1
and (
(column2=value2 or column3=value3)
or (column4=value4 or column5=value5)
)
Please help. 请帮忙。
Your query can be expressed as 您的查询可以表示为
SELECT *
FROM table
WHERE column1=value1
AND (
column2=value2
or column3=value3
or column4=value4
or column5=value5
)
To use above in laravel you can follow Parameter Grouping guide from docs 要在laravel中使用以上内容,您可以遵循docs中的参数分组指南
DB::table('table')
->where('column1', $value1)
->where(function ($query) use ($value2, $value3, $value4, $value5) {
$query->where('column2', $value2)
->orWhere('column3', $value3)
->orWhere('column4', $value4)
->orWhere('column5', $value5)
;
})
->get();
You need to use two nested where()
statements: 您需要使用两个嵌套的where()
语句:
DB::table('the_table')
->where('column', 'val')
->where(function ($q) {
$q->where('column1', 'val1')
->orWhere('column2', 'val2');
})
->where(function ($q) {
$q->where('column3', 'val3')
->orWhere('column4', 'val4');
})
->get()
If you need to pass a variable to the nested where()
, you need to add a use
on the inline function: 如果需要将变量传递给嵌套的where()
,则需要在内联函数上添加一个use
:
DB::table('the_table')
->where('column', $val)
->where(function ($q) use ($val1, $val2) {
$q->where('column1', $val1)
->orWhere('column2', $val2);
})
->where(function ($q) {
$q->where('column3', 'val3')
->orWhere('column4', 'val4');
})
->get()
Try it 试试吧
DB::table('the_table')
->where('column1', 'value1')
->where(function ($query) {
$query->where(function ($query) {
$query->where('column2', 'value2')
->orWhere('column3', 'value3');
})->orWhere(function ($query) {
$query->where('column4', 'value4')
->orWhere('column5', 'value5');
});
})->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.