我必须做出这个 JSON 响应,每个产品都有 colors
并且每种颜色都有很多 images
[
{
"id": 1,
"name": "shirt",
"descriptions": "lorem epsum",
"colors":[
{
"color_name":"red",
"icon":"1.jpeg",
"images": [
{
"url": "1.png"
},
{
"url": "2.png"
},
{
"url": "3.jpeg"
}
]
},
{
"color_name":"blue",
"icon":"1.png",
"images": [
{
"url": "1.png"
},
{
"url": "2.png"
},
{
"url": "3.png"
}
]
}
]
}
]
如何使用 Eloquent 关系制作颜色
?
我应该创建多少个带有外键的表和列?
最佳答案
这里你要制作三个表格
- products -> Product.php(Model name)
- 编号
- 姓名
- 描述
- 创建于
- 更新时间
- colors -> Color.php(Model name)
- 编号
- 产品编号
- 颜色名称
- 创建于
- 更新时间
3) images -> Image(Model name)
- 编号
- color_id
- 网址
- 创建于
- 更新时间
具有关系的三个模型。
Product.php模型
class Product extends Model
{
protected $table = "products";
//get colors
public function colors(){
return $this->hasMany('App\Color','product_id','id');
}
}
Color.php模型
class Color extends Model
{
protected $table = "colors";
//get product
public function product(){
return $this->belongsTo('App\Product','product_id','id');
}
//get images
public function images(){
return $this->hasMany('App\Image','color_id','id');
}
}
Image.php模型
class Color extends Model
{
protected $table = "images";
//get color
public function color(){
return $this->belongsTo('App\Color','color_id','id');
}
}
现在您可以从产品模型访问这些颜色和图像
Controller
$products = App\Product::with('colors.images')->get();
return \Response::json($products->toArray());
关于mysql - Laravel 在一个对象中获取多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57520888/