Paul Denisevich
Paul Denisevich

Reputation: 2414

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?

Upvotes: 0

Views: 414

Answers (1)

John Corry
John Corry

Reputation: 1577

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

Upvotes: 1

Related Questions