php – how to sort results based on pivot table in laravel-ThrowExceptions

Exception or error:

i have three table like this :

  • tour (id name) -> assume (id:1 , name : something)
  • meta (id key) ->assume (id:1 , key: tour_duration)
  • meta_tour (tour_id meta_id value) ->assume (tour_id:1 , meta_id:1 , value: 15)

it’s ManyToMany relationship.

i want to sort tours based on meta value in meta_tour table like this :

tours orderBy tour_duration.value


i tried this :

        Tour::with(['metas' => function ($query) {
        $query->where('key', 'tour_duration')

and this :

        Tour::with(['metas' => function ($query) {
        $query->where('key', 'tour_duration');

and this :

        Tour::whereHas('metas' , function ($query) {
        $query->where('key', 'tour_duration')
              ->orderBy('value', 'desc')

but not working.

How to solve:

You can use a modified withCount():

Tour::withCount(['metas as tour_duration' => function ($query) {
    $query->select('meta_tour.value')->where('key', 'tour_duration');

This uses a subquery to get the value from the pivot table:

select `tours`.*,
  (select `meta_tour`.`value`
   from `metas`
   inner join `meta_tour` on `metas`.`id` = `meta_tour`.`meta_id`
   where `tours`.`id` = `meta_tour`.`tour_id`
     and `key` = 'tour_duration') as `tour_duration`
from `tours`
order by `tour_duration` desc


You can use the withPivot method to order by a pivot table column:

// Tour model
public function meta () {
    return $this->belongsToMany(Meta::class)


To only get the meta with tour duration, try eager loading and adding a where clause on the meta:

$tour->with(['meta' => function ($query) {
    $query->where('key', 'tour_duration');



Tour::join('meta_tour', 'meta_tour.tour_id', '=', '')
    ->join('meta', 'meta_tour.meta_id', '=', '')
    ->where('meta.key', '=', 'tour_duration')
    ->orderBy('meta_tour.value', 'DESC')

Leave a Reply

Your email address will not be published. Required fields are marked *