繁体   English   中英

Laravel口才查询中的SQL查询

[英]SQL query in Laravel Eloquent Query

如何在laravel雄辩中产生如下所示的查询

SELECT *
FROM TABLE
WHERE column1=value1 
and (
        (column2=value2 or column3=value3) 
     or (column4=value4 or column5=value5)
)

请帮忙。

您的查询可以表示为

SELECT * 
FROM table 
WHERE column1=value1 
AND (
       column2=value2 
    or column3=value3 
    or column4=value4 
    or column5=value5
)

要在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();

您需要使用两个嵌套的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()

如果需要将变量传递给嵌套的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()

试试吧

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM