【问题标题】:How to get last updated value of the same record for each day, week, month and year in Laravel eloquent?如何在 Laravel eloquent 中获取每天、每周、每月和每年同一记录的最后更新值?
【发布时间】:2018-09-17 11:54:06
【问题描述】:

这是我的 product_price 表: 请注意,product_id 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"
            }
        ]
    }
}

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

【问题讨论】:

标签: mysql eloquent laravel-5.6


【解决方案1】:

如果您只想获得一条记录,您需要使用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');
                });

【讨论】:

    猜你喜欢
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多