【问题标题】:How to use "OR LIKE" within "AND" condition Laravel如何在“AND”条件下使用“OR LIKE” Laravel
【发布时间】:2016-12-26 16:08:30
【问题描述】:

我是 laravel 新手,在获取记录时遇到了一些问题。表结构如下:

main_categories
------------------
id      name
1       NNN
2       PPP

categories
-----------------------------------
id      name    main_category_id
-----------------------------------
1       abc         1
2       xyz         2
3       lmn         1

services
------------------
id  categories
------------------
1   a:2:{i:0;s:1:"1";i:1;s:2:"3";}
2   a:1:{i:0;s:3:"2";}
3   a:1:{i:0;s:3:"3";}
4   a:2:{i:0;s:1:"1";i:1;s:3:"3";}

服务中存储的类别是序列化的。

在一个表单中,我根据主要类别有下拉列表,每个下拉列表中都有子类别。

帖子数据格式如下:

数组( [0] => 数组( [0] => 1, [1] => 3, ), [1] => 数组( [0] => 2 ) )

像这样的进程 id:每个主类别有 5 个下拉菜单,选项是它们的子类别,我想在子类别或相同的主类别之间放置“或”条件,并在另一组中放置“与”条件其他主要类别的“或”条件。

在原始 SQL 中,我执行以下查询:

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

在 Laravel 中我尝试了以下方法:

$categories = [1,3];

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

但这不起作用。如何在 Laravel 中正确完成。

【问题讨论】:

  • @WalksAway 我试过这个,但它不起作用。它获取所有类别为 1 或 3 的服务,但我只想要那些同时具有 1,3 类别的服务
  • @WalksAway 我已经更新了我的问题。请立即查看

标签: php mysql laravel laravel-5


【解决方案1】:

我相信你正在寻找orWhere()

orWhere('name', 'like', 'John')

【讨论】:

  • 感谢雅达的回复。但它不起作用。它获取所有类别为 1 或 3 的服务,但我只想要那些同时具有 1,3 类别的服务
【解决方案2】:

代码有点难看,但可能适用于您的情况。所以,试试这个:

$categories = [1,3];

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

【讨论】:

  • 感谢您的回复。但是现在我的客户又改变了主意,更新了要求。我已经更新了我的问题,请看一下
【解决方案3】:

我最近在尝试根据给定的值数组搜索数据时遇到了同样的问题。所以通过在包裹的where 内循环orWhere 生成了我正在寻找的查询

$array = [
        [1, 3],
        [2],
        [7,10],
        [5, 9, 13],
        [8],
    ];

    DB::table('services')
        ->where(function ($query) use ($array) {
            foreach ($array as $eachArray) {
                $query->where(function ($query) use ($eachArray) {
                    foreach ($eachArray as $eachElement) {
                        $query->orWhere('categories', 'LIKE', $eachElement);
                    }
                });
            }
        })
        ->dd();

这是上述查询生成器的输出。

select * from `services` where ((`categories` LIKE ? or `categories` LIKE ?) and (`categories` LIKE ?) and (`categories` LIKE ? or `categories` LIKE ?) and (`categories` LIKE ? or `categories` LIKE ? or `categories` LIKE ?) and (`categories` LIKE ?))

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 2011-06-13
    • 2017-09-09
    • 2012-06-04
    • 2017-04-02
    • 2016-04-24
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多