【问题标题】:Search in JSON column using Laravel's eloquent使用 Laravel 的 eloquent 在 JSON 列中搜索
【发布时间】:2017-11-23 23:29:00
【问题描述】:

我一直在使用 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,但它不适合我。

【问题讨论】:

  • 也许这个stackoverflow.com/questions/41942374/… 会帮助你。您还需要在 mysql 中将列 template_ids 的数据类型更改为 JSON
  • 您遇到任何错误?
  • @AlankarMore 我已经添加了链接。我看过这个帖子
  • @RAUSHANKUMAR 是的,如果我使用包含。它给了我 json_contains 不存在。
  • 检查你的mysql版本是否支持json_contains

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

要查看template_ids JSON 字段是否包含针数组中的“任何”值,您需要利用多个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

【讨论】:

  • 在上述情况下是否可以批量删除template_ids?这意味着如果 templates_ids 列中有 1,则从所有行中删除 '1'
  • @SarojShrestha 这个答案可能会有所帮助:Remove array element by value in mysql json
【解决方案2】:

想说什么:

$query = Post::where([]);

$query->where(function($query, $template_ids){
  foreach ($template_ids as $id){
     $query->orWhere('searching_field', 'like', '%'.$id.'%');
  } 
});

$query->get()

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2018-05-20
    相关资源
    最近更新 更多