使用Laravel的口才在JSON专栏中搜索

Far*_*han 5 php mysql laravel eloquent laravel-5

我一直在使用Laravel 5.4的雄辩,我遇到了一个问题.

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

["1","25","48"]
Run Code Online (Sandbox Code Playgroud)

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

$id_access = array:3 [ 
  0 => "1"
  1 => "3"
  2 => "48"
]
Run Code Online (Sandbox Code Playgroud)

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

我试过了:

Post::where('accessable_to',1)->whereIn('template_ids', $template_access_array)->paginate(3);
Run Code Online (Sandbox Code Playgroud)

另外,我试过:

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

已经看过这个,但它不适合我.

sep*_*ehr 6

要查看template_idsJSON字段是否在针阵列中包含“任意”值,您将需要利用多个需要MySQL 5.7的OR'd JSON_CONTAINS条件:

$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);
Run Code Online (Sandbox Code Playgroud)

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"]')
)
Run Code Online (Sandbox Code Playgroud)

哪些目标的记录在其template_idsJSON类型的字段中具有任何这些ID 。

您可能有兴趣阅读相关的Laravel 内部建议