Laravel Eloquent query JSON column with Where In?

别等时光非礼了梦想. 提交于 2019-12-20 02:26:09

问题


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

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