【问题标题】:Laravel Eloquent or Query builder : Use OR conditions inside of AND ConditionsLaravel Eloquent 或查询构建器:在 AND 条件中使用 OR 条件
【发布时间】:2016-12-29 01:28:52
【问题描述】:

数据流:

4-5个主要类别,每个主要类别有10-15个子类别。 属于少数类别的少数服务。类别作为序列化数据存储在服务表中,如下所示:

a:2:{i:0;s:1:"1";i:1;s:2:"3";}
a:1:{i:0;s:3:"2";}
a:1:{i:0;s:3:"3";}
a:2:{i:0;s:1:"1";i:1;s:3:"3";}

发布的表单数据如下:

array(
    [0] => array(
        [0] => 1,
        [1] => 3,
    ),
    [1] => array(
        [0] => 2
    ),
    ....
    ....
    ....
)

将同一主类别中的每个选定类别分组在一个数组中。类别和子类别的数量也不固定

获取记录的普通 SQL

SELECT * FROM `services` WHERE (`categories` LIKE '%"1"%' OR `categories` LIKE '%"3"%') AND (`categories` LIKE '%"2"%') AND ( ... OR ...) AND ( ... OR ...) ....

我已经绑定了这个,但这似乎不起作用。

\DB::table ('services')
->where(function($q) use ($categories) {
    foreach($categories as $category) {
        $q->where('services.categories', 'like', '%"'.DB::raw($category).'"%');
    }
})

【问题讨论】:

    标签: laravel eloquent laravel-5.2


    【解决方案1】:

    使用查询构建器在 Laravel 中查询

    $queryBuilder = \DB::table('services');
    
    //loop to create dynamic where query
    foreach($categories as $category){
    
            //create a query as (condition OR condition)
            $queryBuilder->where(function($query) use($category) {
    
                $query->where('categories', 'LIKE', "%" . $category[0] . "%");
    
                //if count is two then adding the or where clause 
                if(count($category) === 2){
                      $query->orWhere('categories', 'LIKE', "%" . $category[1] . "%");
                }
    
            });
        }
    }
    
    $result = $queryBuilder->get(); //executing the query to get result
    

    【讨论】:

    • 感谢 Max 的回复。但是在代码中我们怎么能硬编码 $category[0] 或 $category[1] 因为类别数组也是动态的。我们不知道有多少类别if(count($category) === 2){ $query->orWhere('categories', 'LIKE', "%" . $category[1] . "%"); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多