php - 如何在 "OR LIKE"条件 Laravel 中使用 "AND"

标签 php mysql laravel laravel-5

我是 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 个下拉菜单,选项是它们的子类别,我想在子类别之间或相同的主类别和与另一组的“AND”条件之间放置“或”条件其他主要类别的“或”条件。

在原始 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 中正确完成此操作。

最佳答案

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

$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).'"%');
        }
    }
});

关于php - 如何在 "OR LIKE"条件 Laravel 中使用 "AND",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39040020/

相关文章:

php - 使用 PDO 查询重置我的服务器

php - Mysql如何过滤结果

PHP - 在类外使用关键字和在类内使用关键字的区别

php - laravel excel读取文件而不导入数据库

php - 调用未定义的方法 Illuminate\Notifications\Messages\MailMessage::via()

php - 需要调用 mysql_real_escape_string() 两次

php - 在 PHP 中构建查询字符串

PHP 字符串作为 mysqli_fetch_array 的数组键

python - Django 迁移 : django. db.utils.OperationalError : (1824, "Failed to open the referenced table ' classroom_user'")

php - MySQL 将变量传递给动态查询