【问题标题】:Laravel Eloquent: get all records sorted by summary price from relationLaravel Eloquent:从关系中获取按汇总价格排序的所有记录
【发布时间】:2016-12-07 16:55:53
【问题描述】:

我有这些模型:

Vendor (id, title)
Service (id, vendor_id, type, price)

关系:Vendor hasMany Service

我需要选择所有供应商,按他们提供的服务的汇总价格排序(具有某种服务类型)

例如,这里是服务表的示例数据:

1  |  1  |  development  |  10
2  |  2  |  development  |  20
3  |  1  |  testing      |  20
4  |  1  |  testing      |  15
5  |  1  |  other        |  15

使用 Eloquent,如何选择所有供应商(提供“开发”和“测试”服务),按所有服务价格汇总排序?

【问题讨论】:

    标签: php mysql sql laravel eloquent


    【解决方案1】:
    $vendor = Vendor::with(['services' => function($query) {
        $query->whereIn('name', ['development', 'testing'])
            ->orderBy('price');
    }])->get();
    

    【讨论】:

    • 这一切我都知道。但是如何获得“summary_price”?没有这样的专栏,我需要在幕后进行数学计算以计算摘要。是否有可能使用 Eloquent 或只有原始 SQL 是解决方案?
    • 'summary price' 是 Service 中价格的总和?
    • 是的,如何获得?看问题。我不需要按价格排序,我需要按每个供应商的所有服务的汇总价格排序。
    • 我认为最好的方法是使用自定义集合,您可能想查看一下:heera.it/extend-laravel-eloquent-collection-object
    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2016-08-04
    • 2021-11-09
    • 1970-01-01
    • 2021-01-25
    • 2014-06-25
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多