php - 使用 Laravel 的 eloquent 在 JSON 列中搜索

标签 php mysql laravel laravel-5 eloquent

我一直在使用 Laravel 5.4 的 eloquent,但遇到了一个问题。

我有一个名为 posts 的数据库表,其中有一列名为 template_ids。它以 json_encoded 格式存储值,例如:

["1","25","48"]

现在,我想根据一组 ID 对我的查询应用过滤器:

$id_access = array:3 [ 
  0 => "1"
  1 => "3"
  2 => "48"
]

我想做的是搜索数据库列 template_ids 中是否存在任何 $id_access 值。

我试过:

Post::where('accessable_to',1)->whereIn('template_ids', $template_access_array)->paginate(3);

另外,我试过:

Post::where('accessable_to',1)->whereRaw("JSON_CONTAINS(template_ids, ".$template_access.")")->paginate(3);

已查看 this ,但这对我不起作用。

最佳答案

要查看 template_ids JSON 字段是否包含 needle 数组中的“任何”值,您需要使用多个 OR'd JSON_CONTAINS需要 MySQL 5.7 的条件:

$ids = ['1', '3', '48'];

Post::where('accessable_to', 1)
    ->where(function ($query) use ($ids) {
        $firstId = array_shift($ids);

        $query->whereRaw(
            'JSON_CONTAINS(template_ids, \'["' . $firstId . '"]\')'
        );

        foreach ($ids as $id) {
            $query->orWhereRaw(
                'JSON_CONTAINS(template_ids, \'["' . $id . '"]\')'
            );
        }

        return $query;
    });

return Post::paginate(3);

Laravel 的查询生成器将生成如下查询:

SELECT * FROM "posts" 
WHERE "accessable_to" = ? AND (
    JSON_CONTAINS(template_ids, '["1"]') OR 
    JSON_CONTAINS(template_ids, '["3"]') OR 
    JSON_CONTAINS(template_ids, '["48"]')
)

它针对在其 template_ids JSON 类型字段中具有任何这些 ID 的记录。

您可能有兴趣阅读相关的 Laravel internals proposal .

关于php - 使用 Laravel 的 eloquent 在 JSON 列中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44669673/

相关文章:

mysql - 使用mysql从UTC格式计算特定月份

javascript - 将字符串从 laravel Controller 转换为 javascript

laravel - 如何避免或诊断Laravel中的错误500

MySQL 中的 Php if 语句用于批量更新

php - SQL:从数据库中选择最多一个数字(大小)

php - 从 TCPDF 在 Chrome 中下载 PDF

PHP 检查进程是否正在运行 (Linux)

mysql - INNER JOIN 相同的表类别和子类别

php - 根据字段最小值连接相关表中的单个项目

php - 如何在中间件 Laravel 中获取请求的 Controller 和操作的名称