我一直在使用 Laravel 5.4 的 eloquent,遇到了一个问题。
我有一个名为posts其中,有一列名为template_ids
。它将值存储在json_encoded
格式如下:
["1","25","48"]
现在,我想根据 ID 数组对查询应用过滤器:
$id_access = array:3 [
0 => "1"
1 => "3"
2 => "48"
]
我想做的是搜索是否有$id_access
值存在于数据库列中,template_ids
.
我试过:
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 https://stackoverflow.com/questions/41942374/json-search-in-laravel-eloquent,但这对我不起作用。
看看是否template_ids
JSON 字段包含 Needle 数组中的“任何”值,您需要使用多个OR
'd JSON_CONTAINS https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#function_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"]')
)
哪些目标记录中具有任何这些 IDtemplate_ids
JSON 类型的字段。
您可能有兴趣阅读相关的 Laravel内部提案 https://github.com/laravel/internals/issues/296.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)