Laravel Eloquent query JSON column with Where In?

后端 未结 2 1451
南笙
南笙 2021-01-21 10:18

I am having trouble querying a json column.

Previously my code was

$query->whereIn(\'user\', $users);

Now i have changed the db type

相关标签:
2条回答
  • 2021-01-21 10:46

    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();
    
    0 讨论(0)
  • 2021-01-21 10:54

    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)
    
    0 讨论(0)
提交回复
热议问题