lundi 25 mai 2020

I used laravel groupBy, but i am trying to sort results by where have many grouped items

I am trying to sort where grouped product_id which has many orders comes first: Here are my codes:

$orderProducts = OrderProduct::where("seller_id", auth()->user()->id)->latest()->get()
            ->groupBy(function ($val){
                return $val->product_id;
});

Result is like:

 ` {
     "1": [
           {
            "id": 8,
            "order_id": "5",
            "product_id": "1",
         }],
     "2": [
           {
            "id": 9,
            "order_id": "5",
            "product_id": "2",
         },
        {
            "id": 10,
            "order_id": "5",
            "product_id": "2",
         }
]}
 `

And i want it sorted like: `
      { 
      "2": [
           {
            "id": 9,
            "order_id": "5",
            "product_id": "2",
         },
        {
            "id": 10,
            "order_id": "5",
            "product_id": "2",
         }
    ],
     "1": [
           {
            "id": 8,
            "order_id": "5",
            "product_id": "1",
         }],
    }
`

where product_id of 2 with many orders comes first and others are ordered according to orders they have. Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire