简体   繁体   English

Laravel - 如何查询数据库中的数组字段是否包含值

[英]Laravel - How to query if an array field in DB contains a value

I have a field in my model Person called jobs that I'm casting as an array.我的模型Person有一个字段,称为jobs ,我将其转换为数组。 jobs is an array of ids related to a Jobs table. jobs是与 Jobs 表相关的 id 数组。 I want to be able to query Person and return all that have a certain id in their jobs array.我希望能够查询 Person 并返回所有在其作业数组中具有特定 id 的内容。 I see that Laravel has a whereIn clause which checks if a database value is in an array but I need the opposite - to check whether a database array contains a value.我看到 Laravel 有一个whereIn子句,它检查数据库值是否在数组中,但我需要相反的 - 检查数据库数组是否包含值。

Am I stuck having to use where('jobs', 'like', '%"' . $job_id . '"%') ?我是否不得不使用where('jobs', 'like', '%"' . $job_id . '"%')

I'm not sure there's an opposite however if you're simply looking to make the query a bit more reusable, you could make it a local scope by adding this to your Person model:我不确定是否有相反的情况,但是如果您只是想让查询更可重用,您可以通过将其添加到您的 Person 模型来使其成为本地范围:

/**
 * Scope a query to only include persons with given job id.
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeHasJob($query, $jobId)
{
    return $query->where('jobs', 'like', "%\"{$jobId}\"%");
}

The name of the scope hasJob may interfere with the parent QueryBuilder method has so you might have to come up with a different name for it.范围的名称hasJob可以与母QueryBuilder的方法干扰has ,所以你可能不得不拿出它不同的名称。

Now you can use Person::hasJob($job->id) .现在您可以使用Person::hasJob($job->id) However rather than storing the job ids in a column as an array, you should consider creating a pivot table to map the relationships between a person and job.但是,与其将作业 ID 作为数组存储在列中,不如考虑创建一个数据透视表来映射人员和作业之间的关系。 You can do this using php artisan:您可以使用 php artisan 执行此操作:

php artisan generate:pivot persons jobs php artisan migrate php artisan generate:pivot persons jobs php artisan migrate

Then you need to add the relationship into your Person model:然后您需要将关系添加到您的 Person 模型中:

/**
 * The person's jobs
 */
public function jobs()
{
    return $this->belongsToMany('App\Job');
}

So you can query your Person model by Job like this:所以你可以通过 Job 查询你的 Person 模型,如下所示:

Person::whereHas('jobs', function ($query) {
    return $query->whereId($job->id);
});

Laravel includes whereJsonContains(): So your field jobs that you are casting as an array, that can query as : Laravel 包括whereJsonContains():所以你的现场jobs你作为一个数组进行转换,可以查询为:

->whereJsonContains('jobs', 3)

That way worked for me ...这种方式对我有用......

<!-- If you have a collection of variable like this: --> $category_id = 1,2,3,...;
$category_id = $_POST['category_id'];

<!--following function used to conver as an array -->
$myArray = explode(',', $category_id);

<!-- If you already have array data you can pass this to the following query -->
$data = DB::table('tablename')->select('*') ->whereIn('catcode', $myArray)->get();

You could use something like this query.您可以使用类似此查询的内容。

$k = ["359045532","359079612","359079372","359081292","359081052","359086332","359086092","359111892","359111652"];

Modal::whereIn('myitems', $k)->get(); 

I am adding a little more info to Zubayer Hossain's answer我在Zubayer Hossain 的回答中添加了更多信息

The data types have to match:
// [1, 2]
->whereJsonContains('players', 1)   // Works.
->whereJsonContains('players', '1') // Doesn't work.

// ["1", "2"]
->whereJsonContains('players', '1') // Works.
->whereJsonContains('players', 1)   // Doesn't work. 
                                                                      

whereJsonContains can be used in cases where we need to check if a value matches a json encoded field in our table. whereJsonContains可用于我们需要检查值是否与表中的 json 编码字段匹配的情况。

Courtesy : https://newbedev.com/php-wherejsoncontains-and-with-laravel-example礼貌: https : //newbedev.com/php-wherejsoncontains-and-with-laravel-example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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