简体   繁体   中英

Laravel Eloquent: get all records sorted by summary price from relation

I have these models:

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

Relationship: Vendor hasMany Service

I need to select all vendors, sorted by the summary price of the services they provide (with the certain service type)

For example, here's the sample data for services table:

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

With Eloquent, how to select all vendors (who provide "development" and "testing" services), sorted by summary of all services price?

$vendor = Vendor::with(['services' => function($query) {
    $query->whereIn('name', ['development', 'testing'])
        ->orderBy('price');
}])->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM