3
我有一個允許用戶創建項目和分配任務的系統。現在我正在試圖限制視圖來顯示由當前用戶創建或分配給當前用戶的所有項目。我有三個表users
,projects
和project_user
建立了多對多的關係。凡項目表有一列user_id
爲誰「擁有」它。在Laravel中合併兩個雄辯的集合
我嘗試使用merge method基於this question收藏,但我不能得到它的工作。
$projects = new \Illuminate\Database\Eloquent\Collection();
$userProjects = Project::where(array('company_id' => Auth::user()->company_id, 'user_id' => Auth::user()->id))
->orderBy('created_at', 'asc')
->get();
//foreach($userProjects as $up){
$projects = $projects->merge($userProjects);
//}
$assignedProjects = User::where('id', Auth::user()->id)->with('project')->orderBy('created_at', 'asc')->get();
foreach($assignedProjects as $assigned){
$projects = $projects->merge($assigned->project);
}
dd($projects->all());
然後我嘗試轉換爲數組,然後手動創建一個對象,但那並沒有相當工作,我也擔心資源。
$userProjects = Project::where(array('company_id' => Auth::user()->company_id, 'user_id' => Auth::user()->id))
->orderBy('created_at', 'asc')
->get()->toArray();
$assignedProjects = User::where('id', Auth::user()->id)->with('project')->orderBy('created_at', 'asc')->get()->toArray();
$projects = array_merge((array) $userProjects, (array) $assignedProjects[0]['project']);
$cleaned = array_unique($projects, SORT_REGULAR);
$merge = array('projects' => (object) $cleaned);
$projects = (object) $merge;
dd($projects);
的目標是以某種方式讓這些到集合合併,以便我可以使用$ project-> title(例如)從視圖訪問它。
當我剛剛爲用戶「擁有」項目執行此操作時工作正常,現在如何讓它工作以顯示用戶和項目分配給用戶的兩個項目?
你是真棒,所以非常容易,非常感謝你!對於其他人尋找這種情況下的鏈接:https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence – Derek