簡體   English   中英

Laravel屬於ToMany關系條件

[英]Laravel belongsToMany relation condition

我已經使用belongsToMany函數創建了多對多關系:

class Doctor extends Model
{
...
    public function categories()
    {
        return $this->belongsToMany('App\Category', 'doctors_to_categories', 'doctor_id', 'category_id');
    }
...
}

現在,我想創建具有多對多條件的查詢。 在SQL中將是:

SELECT *
FROM `doctors`
JOIN `doctors_to_categories`
    ON `doctors_to_categories`.`doctor_id` = `doctors`.`id`
WHERE `doctors_to_categories`.`category_id` = 1

我試圖做到這一點,如:

$doctors = Doctor::with(['categories' => function($query) {
    $query->where('category_id', '=', 1);
}])->get();

要么

$doctors = Doctor::with(['categories' => function($query) {
    $query->where('categories.id', '=', 1);
}])->get();

但這是行不通的。 任何想法應該如何? 謝謝你的幫助。

使用->with()實際上並不限制Doctor::...->get()查詢的結果; 它只是告訴Laravel在relationships屬性中返回什么。 如果您實際上只想強制要求退回具有1類關系的Doctor,則需要使用whereHas()

$doctors = Doctor::whereHas('categories', function($query) {
  $query->where('categories.id', '=', 1); 
  // `id` or `categories.id` should work, but `categories.id` is less ambigious
})->get();

with()函數實際上並未在查詢中引入聯接,它只是將所有模型的關系作為第二個查詢來加載。 因此, with()函數不可能更改原始結果集。

您正在尋找的是whereHas() 這會將WHERE EXISTS子句添加到現有查詢中。

$doctors = Doctor::with('categories')->whereHas('categories', function ($query) {
    $query->where('categories.id', 1);
})->get();

您可以添加whereHas條件這一點。 請嘗試以下代碼:

$doctors = Doctor::with('categories')->whereHas('categories', function($query) {
        $query->where('id', 1);
    })->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM