簡體   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