2017-07-24 99 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为如何保存模型,这是很简单的。