如何在LaravelEloquent中获得同一记录的每一天、每一周、每一个月和每一年的最后更新值?

hmmo2u0o  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(374)

这是我的产品价格表:

请注意,产品标识1在同一天更新了多次。这是我当前的查询:

$product = ProductPriceModel::where(['product_id' => $request->product_id])->distinct()->latest()->get()->groupBy(function ($date) {
                    return Carbon::parse($date->created_at)->format('Y-m-d');
                });

结果是:

"data": {
    "productDetails": {
        "2018-09-17": [
            {
                "min_price": 0,
                "max_price": 1150,
                "price_diff": "425"
            },
            {
                "min_price": 100,
                "max_price": 200,
                "price_diff": "-945"
            }
        ],
        "2018-09-10": [
            {
                "min_price": 1070,
                "max_price": 1120,
                "price_diff": "-30"
            },
            {
                "min_price": 1100,
                "max_price": 1150,
                "price_diff": "15"
            },
            {
                "min_price": 1080,
                "max_price": 1140,
                "price_diff": "0"
            }
        ]
    }
}

我期望它返回的是每个日期只有一个记录。在上述查询中需要做哪些更改才能为每个日期获得一条记录?

5w9g7ksd

5w9g7ksd1#

如果你只想得到一张你需要使用的唱片 first() 代替 get() 请试一试

$product = ProductPriceModel::where(['product_id' => $request->product_id])->distinct()->latest()->first()->groupBy(function ($date) {
                    return Carbon::parse($date->created_at)->format('Y-m-d');
                });

相关问题