我有两张桌子。
分类
id(int)
photo_id(int)
name(string)
created_ad(datetime)
updated_at(datetime)
产品
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
(会给我类别表中的类别名称)
但是,如果我想要多个,我该怎么做?
我正在尝试使用列category_id
并将其设置为字符串类型,而不是使用json中的所有ID,它的工作方式,而不是我在视图中显示的方式?
我无法在数据库列类型json中创建这是mariaDB。
答案 0 :(得分:0)
您需要创建many-to-many关系才能为每个项目设置多个类别。你可以想到它,因为每个项目都可以有很多类别,每个项目都可以有很多项目。
首先,您需要创建一个数据透视表
category_id
item_id
。
belongsToMany
然后将Category
关系添加到Item
和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; }}
}
然后,您可以在刀片模板中执行此操作。
java.lang.Integer
查看docs如何保存模型,这非常简单。