2014-10-17 122 views
0

我跑在我的laravel應用此查詢,降序模型關係laravel

$project = Project::leftJoin('organisation_user', 'organisation_user.organisation_id', '=', 'projects.organisation_id') 
       ->where('organisation_user.user_id', '=', ResourceServer::getOwnerId()) 
       ->whereNotNull('projects.organisation_id') 
       ->get(); 

這將返回希望它,我就可以做樞軸數據這一負載對組織的項目是數據也有關係。

$project->load('organisations');

什麼,我想從這個角度做的是在組織的樞軸數據負載是可能的,在我的腦袋好像我想通過關係下降。

回答

1

假設您已將多對多關係設置爲projectorganization模型,您可以跳過此連接並一次完成所有操作。

$project = Project::has('organizations')->with(['organizations'=> function($query){ 
    $query->where('user_id', ResourceServer::getOwnerId()); 
}])->get(); 

或者,改變一下事情並調用嵌套關係。

$organization = Organization::with('projects.organizations')->where('user_id', ResourceServer::getOwnerId())->first(); 

return $organization->projects; 

如果您需要更多的數據透視表的數據包括在內,你可以添加withPivot()到你的人際關係。

+0

這看起來幾乎正是我想要做的 - 但(抱歉) - 項目可以由組織擁有,並且該組織可以擁有任意數量的用戶。這些存儲在一個名爲'organisation_user'的數據透視表中,我需要根據'organisation_user.user_id'來查詢這個數據。我不能爲我的直播弄清楚如何做到這一點。 – Udders 2014-10-17 16:11:36

+0

我仍然可能對你想要做的事情有些困惑,但我已經加入了答案。急切地加載嵌套關係可能會訣竅。 – 2014-10-17 17:02:02