So in Laravel 5 there's the handy thing called JSON Where Clauses using MySQL's new ability to store and fetch JSON stored in a column:

User::where('meta->colors', 'red')->get()

would return all rows, where colors in the column meta would be set to red.

现在假设colors不是一个字符串,而是一个包含多种 colored颜色 的数组(colors => ['red', 'blue', 'green']).

What would be an efficient way to retrieve all rows, where colors contains e.g. the value red?

推荐答案

JSON_CONTAINS()正是你想要的:

JSON_CONTAINS(target, candidate[, path])

Indicates by returning 1 or 0 whether a given candidate JSON document is contained within a target JSON document, or—if a path argument was supplied—whether the candidate is found at a specific path within the target. — 12.16.3 Functions That Search JSON Values

Currently, Laravel's query builder does not provide a corresponding API. There's an open internals proposal for it though.

In the meantime, you can execute a raw query:

\DB::table('users')->whereRaw(
    'JSON_CONTAINS(meta->"$.colors", \'["red"]\')'
)->get();

Which would return all users that have "red" in their meta->colors JSON field. Note that the -> operator requires MySQL 5.7.9+.

You can also call the whereRaw() directly on an Eloquent model.

Laravel 5.6

从5.6版本开始,Laravel的查询生成器包含一个新的whereJsonContains方法.

Laravel相关问答推荐

AJAX响应中未定义的全名

Laravel AppServiceProvider 中的代码在通过 DeployHQ 部署时停止 Composer 和构建

通过 laravel 中的 url 传递多个字符串作为参数以从数据库中删除特定数据

未定义防护 [api] 的授权驱动程序 [api]

向 Laravel 模型查询添加计算字段

如何判断用户Electron邮件是否已存在

Laravel 中的 index()" 是什么意思?

如何在 laravel 中安装 PHPExcel 库?

Laravel 验证 - 输入必须是数组中的项目之一

Laravel 5 - 多对多 - Attach versus Save

Homestead:文件夹映射到错误的文档根目录

我如何从给定的日期时间 struct 创建Carbon 对象?

如何将对象(模型类型对象)插入到 Laravel 中特定索引号的集合对象中?

如何在不使用视图的情况下使用 Laravel 4 发送Electron邮件?

如何在 Laravel 视图中找到当前语言?

如何使用 Laravel 测试授权重定向?

Laravel 5.4 - Mix - 如何运行浏览器实时重新加载

如何在laravel中获取列值的平均值

Laravel 5 - 从控制器级别的所有请求对象中删除参数

Laravel 4 - 文件上传