问题
I am having trouble querying a json column.
Previously my code was
$query->whereIn('user', $users);
Now i have changed the db type to JSON column and am trying to modify the code for the new version.
In RAW MYSQL this works
JSON_CONTAINS(user, '"tom","Bill"')
But when i put it in eloquent / php it keeps failing or returning noting. Here i am passing in an array of Users, previous using an WhereIn which works in raw SQL
$leads->whereRaw("JSON_CONTAINS(user, '"$users"')")
Any idea how to make it work in Laravel so i can pass in an array of strings, query them against the json column which contains an array of strings too.
My Json colum has data like so
["Paul", "Tom", "Bob"]
回答1:
MySQL expects a JSON string:
$leads->whereRaw('JSON_CONTAINS(user, ?)', [json_encode($users)])
In Laravel 5.6.24 you can use whereJsonContains()
:
$leads->whereJsonContains('user', $users)
回答2:
If $users
is array of names then you should iterate over it and add orWhereRaw
condition, note that orWhereRaw can accept an array of parameter:
$users = ["Tom", "Bob"];
foreach( $users as $user) {
$leads->orWhereRaw("JSON_CONTAINS(user, ?)", [$user]);
}
$leads = $leads->get();
来源:https://stackoverflow.com/questions/48188529/laravel-eloquent-query-json-column-with-where-in