假設我有3個表格,posts
,post_images
和post_links
。 post.id是post_images和post_links中的外鍵。正確的查詢從3個表中獲取數據並將其顯示爲laravel中的單個元素?
每個帖子都有多個圖片。
我需要一個數據,其中包含後,其圖像及其鏈接作爲單個元素/數組項。如果有3個帖子,我需要3個數組,每個數組包含帖子圖像和鏈接。
到目前爲止我的代碼,
$data = DB::table('posts')
->join('post_images','posts.id' ,'=', 'post_images.post_id')
->join('post_links','posts.id' ,'=', 'post_links.post_id')
->select('posts.*')
->get();
與我得到的所有記錄上面的查詢加盟,如果我有3條記錄,每3個圖像,我得到9條,我只需要3個員額與其數據作爲其子陣列。
有什麼建議嗎?
爲什麼不能用雄辯的?如果你建立了適當的關係,你可以做'$ data = Post :: with('images','links') - > get();'你就可以得到你所要求的結果。 –