2017-02-09 61 views
0

在Laravel我有一個模型,看起來像這樣:Laravel雄辯預先加載混亂

class Recipient extends Model 
{ 
    public $table = 'recipients'; 

    public function location() 
    { 
     return $this->belongsTo('App\Location'); 
    } 

    public function teams() 
    { 
     return $this->belongsToMany('App\Team'); 
    } 


    public function company() 
    { 
     return $this->belongsTo('App\Company'); 
    } 

} 

若要查詢模型我這樣做:

$recipients = Recipient::with('location') 
          ->with('teams') 
          ->where('company_id',Auth::user()->company_id) 
          ->where('teams.id', 10) 
          ->get(); 

在這樣做時,我得到一個錯誤說laravel找不到teams.id,因爲它只查詢父收件人表。想知道我做錯了什麼,我認爲with方法是急於加載/內部連接記錄?我是否需要使用DB:內部連接?或者我錯過了什麼?

回答

1

使用whereHas方法是:

Recipient::with('location') 
    ->where('company_id', auth()->user()->company_id) 
    ->whereHas('teams', function($q){ 
     return $q->where('id', 10); 
    }) 
    ->get(); 
0

嘗試是明確的,並添加一個select語句。有時,沒有選擇時,關係不會顯示出來。包含其他ID將不起作用