2015-09-13 184 views
1

我有2個表格:CalendarUserCalendar有一對多的關係UserUser具有通過parentID與自身的關係:Laravel 5雄辯多重關係

//model Calendar.php 
    public function users() 
    { 
     return $this->belongsTo(User::class,'userID'); 
    } 
//model User.php 
    public function parent() 
    { 
     return $this->belongsTo(self::class,'parentID','id'); 
    } 

我已經選擇它就像我想,但我想補充:

where('users.parent.parentID',$userID)->orWhere('users.parent.parentID',$userID); 

但我不」我認爲它會起作用。我試圖加入,但我不知道如何。我已經試過:

$calendar = calendar::with('users','users.parent')->get()->where('users.parent.parentID',$userID); 

$calendar = calendar::with('users','users.parent')->get()->where('users.parentID',$userID); 
+0

get()在模型查詢中排在最後。 – Gokigooooks

回答

1
Calendar::with('users') 
     ->whereHas('users', function($query) use ($userID) { 
     $query->where('parentID', $userID)->orWhereHas('parent', function($query) use ($userID) { 
      $query->where('parentID', $userID); 
     }); 
    })->get(); 

這將加載喲所有擁有parentID等於$ userID的用戶或者具有相同條件的父用戶。對於加載關係,您必須使用with函數,用於過濾其內部的關係使用回調,用於過濾關係所有者使用函數whereHasorWhereHas