2015-09-13 93 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