2017-06-20 13 views
0

假設我有3個表格,posts,post_imagespost_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個員額與其數據作爲其子陣列。

有什麼建議嗎?

+0

爲什麼不能用雄辯的?如果你建立了適當的關係,你可以做'$ data = Post :: with('images','links') - > get();'你就可以得到你所要求的結果。 –

回答

2

這裏是PostImage模型

類PostImage擴展型號

{ 
    public function post() { 
     return $this->belongsTo(Post::class); 
    } 
} 

這裏是PostLink模型

class PostLink extends Model 
{ 
    public function post() { 
     return $this->belongsTo(Post::class); 
    } 
} 

這裏是Post模型

class Post extends Model 
{ 

    public function links() { 
     return $this->hasMany(PostLink::class); 
    } 

    public function images() { 
     return $this->hasMany(PostImage::class); 
    } 
} 

在視圖中,你可以達到你需要的一切。

@foreach ($posts as $post) 

    {$post->title} <br> 

    @foreach ($post->links as $link) 

     {$link->url} <br> 

    @endforeach 

    @foreach ($post->images as $image) 

     {$image->src} <br> 

    @endforeach 

@endforeach 

如果您想使用較少的查詢,您可以使用預先加載來第一次獲取所有這些數據。 Eager Loading Laravel

應該是這個樣子

$posts = Post::with('images','links')->get(); 
相關問題