yvl
yvl

Reputation: 660

Using sortBy after groupBy in connected table by with

I am using collection and grouping the raws with same value.

    $hotels = Hotel::with("plans")->get();

    $group = $hotels
    ->groupBy(function ($hotel) {
        return $hotel->place_name;
    })
    ->map(function($sort){
        return $sort->sortBy("plans.plan_price");
    });

Also I need to use sortBy on the connected table's value. But I can't reach the table that comes with with.

The structure is like below.

Collection {#283 ▼
  #items: array:4 [▼
    "Hilton" => Collection {#290 ▼
      #items: array:3 [▼
        0 => Hotels {#233 ▼
          #table: "hotels"
          +with: array:4 [▼
                 0 => "location"
                 1 => "plans"
                 2 => "infos"
                 3 => "images"
               ]
          #attributes: array:5 [▶]
          #original: array:5 [▶]   
          #relations: array:4 [▶]
        }
      ]
    }
    "Dedeman" => Collection {#287 ▶}
    "Rapsodi" => Collection {#288 ▶}
    "Blur" => Collection {#286 ▶}
  ]
}

How can I grab with's items and sort plans's value which is plan_price.

Upvotes: 0

Views: 37

Answers (2)

Karan Sadana
Karan Sadana

Reputation: 1373

you can use it like below:-

$modelCollection = Model::with(['relationship'=>function($query){
   $query->OrderBy('plan_price','asc');
}])->get()->groupBy('your_fied');

Upvotes: 0

yvl
yvl

Reputation: 660

I solved the problem with using like below.

    $hotels = Hotel::with(["plans" => function($query){
        $query->orderBy("plans.plan_price");
    }])->get();

    $group = $hotels
    ->groupBy(function ($hotel) {
        return $hotel->place_name;
    });

    return $group;
    // dd($group);

Upvotes: 1

Related Questions