2016-06-06 55 views
-1

我得到了兩張桌子:「產品」和「產品照片」。 每個產品都有一個唯一的id = Product_ID。 每個productPhoto都有一個唯一的id = ProductPhoto_ID。 在我的表productPhoto中也有照片,這在我的遷移中是這樣指定的:$ table-> binary('photo');這是爲了上傳圖片。2張桌子之間的鏈接laravel

在表格產品中,我有ProductPhoto_ID(這是一種關係)。 但我如何添加'照片'?

+0

請在https://laravel.com/docs/5.2/eloquent-relationships一些研究。你的問題不清楚。 –

回答

1

您需要爲每個表格創建模型。

對於表/列名稱,最好使用laravel約定。

所以我會打電話給他們這樣的:

產品 - ID - 等等......

照片 - ID - PRODUCT_ID - 等等......

然後創建2型號:

class Product extends Model 
    { 
     protected $table = 'products'; 

     public function photos() 
     { 
      return $this->hasMany('App\Photos'); 
     } 
    } 

    class Photo extends Model 
    { 
     protected $table = 'photos'; 

     public function product() 
     { 
      return $this->belongsTo('App\Product','product_id'); 
     }  
    } 

然後在你的控制器中你會很好地得到這樣的關係:

$ product = Product :: find($ id) - > with('photos');

這將返回一個帶有稱爲照片的屬性的產品模型,該屬性是與其相關的所有照片模型的集合。

看看https://laravel.com/docs/5.1/eloquent-relationships

乾杯