我一直在使用 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/