Laravel Eloquent 使用 Where In? 查询 JSON 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48188529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:13:47  来源:igfitidea点击:

Laravel Eloquent query JSON column with Where In?

phpmysqllaraveleloquentlaravel-eloquent

提问by Logon

I am having trouble querying a json column.

我在查询 json 列时遇到问题。

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.

现在我已将 db 类型更改为 JSON 列,并且正在尝试修改新版本的代码。

In RAW MYSQL this works

在 RAW MYSQL 中这有效

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

但是当我把它放在 eloquent/php 中时,它总是失败或返回注释。在这里,我传入了一组用户,之前使用的是在原始 SQL 中工作的 WhereIn

$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.

任何想法如何使它在 Laravel 中工作,以便我可以传入一个字符串数组,并针对包含字符串数组的 json 列查询它们。

My Json colum has data like so

我的 Json colum 有这样的数据

["Paul", "Tom", "Bob"]

回答by Jonas Staudenmeir

MySQL expects a JSON string:

MySQL 需要一个 JSON 字符串:

$leads->whereRaw('JSON_CONTAINS(user, ?)', [json_encode($users)])

In Laravel 5.6.24 you can use whereJsonContains():

在 Laravel 5.6.24 中,您可以使用whereJsonContains()

$leads->whereJsonContains('user', $users)

回答by YouneL

If $usersis array of names then you should iterate over it and add orWhereRawcondition, note that orWhereRawcan accept an array of parameter:

如果$users是名称数组,那么您应该对其进行迭代并添加orWhereRaw条件,请注意orWhereRaw可以接受参数数组:

 $users = ["Tom", "Bob"];

 foreach( $users as $user) {
      $leads->orWhereRaw("JSON_CONTAINS(user, ?)", [$user]);
 }

 $leads = $leads->get();