简体   繁体   中英

Laravel Eloquent query JSON column with Where In?

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"]

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)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM