mysql - Laravel 在一个对象中获取多个对象

标签 mysql json laravel laravel-5 eloquent

我必须做出这个 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 关系制作颜色

我应该创建多少个带有外键的表和列?

最佳答案

这里你要制作三个表格

  1. products -> Product.php(Model name)
  • 编号
  • 姓名
  • 描述
  • 创建于
  • 更新时间
  1. 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/

相关文章:

php - 在 windows 10 中安装 composer 失败缺少 openssl 扩展

mysql - SQL LEFT JOIN 不过滤

mysql - "Column ' 选项类型 ID ' cannot be null..."

json - 使用 F# 解析 JSON(不是序列化)

java - 反序列化通用类 Jackson 或 Gson

php - 在现代框架中使用路由文件的原因是什么?

php - MySQL数据库: one media table or one table for images and one for videos?

mysql - 在 MySQL 触发器中获取 CURRENT_USER 返回不正确的值

PHP MySQL 最接近邮政编码

java - Volley每次从SERVER而不是缓存获取数据