繁体   English   中英

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

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

我的模型Person有一个字段,称为jobs ,我将其转换为数组。 jobs是与 Jobs 表相关的 id 数组。 我希望能够查询 Person 并返回所有在其作业数组中具有特定 id 的内容。 我看到 Laravel 有一个whereIn子句,它检查数据库值是否在数组中,但我需要相反的 - 检查数据库数组是否包含值。

我是否不得不使用where('jobs', 'like', '%"' . $job_id . '"%')

我不确定是否有相反的情况,但是如果您只是想让查询更可重用,您可以通过将其添加到您的 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}\"%");
}

范围的名称hasJob可以与母QueryBuilder的方法干扰has ,所以你可能不得不拿出它不同的名称。

现在您可以使用Person::hasJob($job->id) 但是,与其将作业 ID 作为数组存储在列中,不如考虑创建一个数据透视表来映射人员和作业之间的关系。 您可以使用 php artisan 执行此操作:

php artisan generate:pivot persons jobs php artisan migrate

然后您需要将关系添加到您的 Person 模型中:

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

所以你可以通过 Job 查询你的 Person 模型,如下所示:

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

Laravel 包括whereJsonContains():所以你的现场jobs你作为一个数组进行转换,可以查询为:

->whereJsonContains('jobs', 3)

这种方式对我有用......

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

您可以使用类似此查询的内容。

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

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

我在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可用于我们需要检查值是否与表中的 json 编码字段匹配的情况。

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

暂无
暂无

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

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