samedi 19 août 2017

Laravel: Grouping of rows

I have a model called Order like so:

class Order extends Model
{
     public function offer()
     {
     return $this->belongsTo(Offer::class);
     }  
}

Example rows may look like this

id  quantity    offer_id
15  5           20
20  1           21
25  3           20
30  2           27
35  1           20
40  1           21

I want to group all orders by offer_id using Laravel Eloquent to give the following output:

[
    [20] => [
        // order 15,
        // order 25,
        // order 35,
    ],
    [21] => [
        // order 20,
        // order 40,
    ]
    [27] => [
        // order 30,
    ]
]

How can I do this efficiently? I have tried the following:

Order::groupBy('offer_id)->get();

But this just hides orders with the same offer_id.

Note that I will ideally like to do this all in Laravel Elqouent, so opposed to doing some post-processing.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2x0PDBS
via IFTTT

Aucun commentaire:

Enregistrer un commentaire