2014-11-25 78 views

回答

0

隨着預先加載

$goods = Good::with('tags')->get(); 

foreach ($goods as $good) { 
    // each goods 
    echo $good->title; 

    foreach ($good->tags as $tag) { 
     // each tag for that goods 
     echo $tag->title; 
    } 
} 

每個返回良好運行模式將有其附着的標籤的集合。

Docs - Eloquent - Eager Loading

0

好吧,首先讓寫在你的模型的關係:

很好的模型(代表產品表)

public function getTags() 
{ 
    return $this->belongsToMany('Tag','good_tag','good_id','tag_id'); 
} 

標籤模型(代表標籤表)這是獲得特定標籤的商品的反向關係


public function getGoods() 
{ 
    return $this->belongsToMany('Good','good_tag','tag_id','good_id'); 
} 

我們檢索所有商品和在這裏他們的標籤的代碼:

$goods=Good::All(); 
    foreach($goods as $good) 
    { 
     echo $good->title; 
     echo "Tags: "; 
     foreach($good->getTags as $tag) 
     { 
      echo $tag->title." "; 
     } 

    } 
相關問題