Select, where JSON Array contains

假如想象 提交于 2020-02-20 07:06:45

问题


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.

Now let's say colors is not a string, but an array containing multiple colors (colors => ['red', 'blue', 'green']).

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


回答1:


JSON_CONTAINS() does exactly what you're looking for:

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

As of the 5.6 release, Laravel's query builder contains a new whereJsonContains method.




回答2:


I think a way would be using the like operator:

User::where('meta->colors', 'like', '%"red"%')

However, this would only work if the values never contain the character " and the delimiters wouldn't change.




回答3:


An update for this answer, according to MySQL or MariaDb, the correct syntax must be JSON_CONTAINS(@json, 'red', '$.colors'), and is necessary to use JSON_EXTRACT.

So them, the code inside Laravel (for version 5.5 or less).

Like say @Elwin, meta column must contains the following JSON: { "colors": ["red", "blue", "green"] }

User::whereRaw("JSON_CONTAINS(JSON_EXTRACT(meta, '$.colors'), '\"{$color}\"')")

Remember to use double quotes in value sentence.
JSON_CONTAINS(JSON_EXTRACT(meta, '$.colors'), '"red"')




回答4:


The whereIn method verifies that a given column's value is contained within the given array. Try this:

$colorArray = ['red', 'blue', 'green'];

$user = User::whereIn($meta->color, $colorArray)->get();

More about Laravel's whereIn.



来源:https://stackoverflow.com/questions/46055223/select-where-json-array-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!