Laravel 5.4获取id的json数组

时间:2017-07-24 16:58:47

标签: php mysql json laravel laravel-5

我有两张桌子。

  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)

  3. 类别模型

    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并将其设置为字符串类型,而不是使用json中的所有ID,它的工作方式,而不是我在视图中显示的方式?

    2. 我无法在数据库列类型json中创建这是mariaDB。

1 个答案:

答案 0 :(得分:0)

您需要创建many-to-many关系才能为每个项目设置多个类别。你可以想到它,因为每个项目都可以有很多类别,每个项目都可以有很多项目。

首先,您需要创建一个数据透视表 category_id item_id

  1. category_item belongsToMany
  2. 然后将Category关系添加到Itemclass 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; }}
    }
    

    然后,您可以在刀片模板中执行此操作。

    java.lang.Integer

    查看docs如何保存模型,这非常简单。