2017-07-24 97 views
0

我有兩個表。Laravel 5.4把json數組的id的

  1. 分類 id(int) photo_id(int) name(string) created_ad(datetime) updated_at(datetime)

  2. 項目 id(int) category_id(int) photo_id(int) name(string) description(text) created_ad(datetime) updated_at(datetime)

分類模型

class Category extends Model 
{ 

    protected $fillable = ['name', 'photo_id']; 


    public function photo() 
    { 

     return $this->belongsTo('App\Photo'); 

    } 
} 

個項目模型

class Items extends Model 
{ 

    protected $fillable = [ 
     'name', 'category_id', 'photo_id', 'description' 
    ]; 


    public function category() 
    { 

     return $this->belongsTo('App\Category'); 

    } 


    public function photo() 
    { 

     return $this->belongsTo('App\Photo'); 

    } 
} 

我想給項目 類別的一個以上的ID,如果它只有一個ID,我知道如何顯示此

$item->category->name(會給我類別從類別表的名稱)

但是,如果我想要多於一個,我該怎麼做?

  1. 我試圖採取列category_id,並使其string類型不是採取所有ID的JSON,它的工作,但比我如何在視圖中顯示這個?

  2. 我不能在數據庫列類型json這是mariaDB。

+0

您必須創建數據透視表。 – Laerte

+0

您定義了'belongsTo'關係,因此一個項目只能有一個類別,在這種情況下項目不能有多個類別。 –

回答

0

您需要創建一個many-to-many關係,以使每個項目具有多個類別。你可以想象它,因爲每個物品可以有很多類別,每個物品可以有很多物品。

首先您需要創建數據透視表category_item

  • category_item category_id item_id
  • 然後belongsToMany關係添加到你CategoryItem模型。

    分類模型

    class Category extends Model 
    { 
    
        protected $fillable = ['name', 'photo_id']; 
    
    
        public function photo() 
        { 
    
         return $this->belongsTo('App\Photo'); 
    
        } 
    
        /** 
        * The items that belong to the category. 
        */ 
        public function items() 
        { 
    
         return $this->belongsToMany('App\Item'); 
    
        } 
    } 
    

    項目模型

    class Item extends Model 
    { 
        // 
    
        protected $fillable = [ 
         'name', 'category_id', 'photo_id', 'description' 
        ]; 
    
    
        /** 
        * The categories that belong to the item. 
        */ 
        public function categories() 
        { 
    
         return $this->belongsToMany('App\Category'); 
    
        } 
    
        public function photo() 
        { 
    
         return $this->belongsTo('App\Photo'); 
    
        } 
    } 
    

    這樣,你會做你的刀模板。

    @foreach ($item->categories as $category){ 
        {{ $category->name; }} 
    } 
    

    退房的docs爲如何保存模型,這是很簡單的。