skip to Main Content

I have a model Facility that has rates (tariffs). The Rate model has a relationship to a RateType. The RateType has a column weight. I want to sort the Facility’s rates based on those weights. I would like to always have this ordering so I’d put it into the relationshop function directly. I cant get it to work, though. I always get some mix up with the column and table names and I feel like I am missing a very easy solution.

<?php

class Facility extends Model
{
    public function rates()
    {
        return $this->hasMany(Rate::class)->orderBy(
            // :(
        );
    }
}

class Rate extends Model
{
    public function rateType()
    {
        return $this->belongsTo(RateType::class);
    }
}

The RateType doesnt have the relationship function back to Rate, I guess thats not the problem.

Any help is greatly appreciated.

2

Answers


  1. You need to try below code.

    Facility::with([
    'rates' => function($q){
         $q->orderBy('your_column', 'desc');
     }
    ])->get();
    
    Login or Signup to reply.
  2. You can just join the table in your rates relationship from Facility model, which allows you to call orderBy or orderByDesc on any rate_types column

    e.i. (assumed standard column names use by your relationship)

    class Facility extends Model {
    
        public function rates() {
            return $this->hasMany(Rate::class)
                ->join('rate_types', 'rate_types.id', '=', 'rates.rate_type_id')
                ->orderBy('rate_types.weight', 'ASC');
                //->orderByDesc('rate_types.weight');
        }
    }
    

    Then you can do something like

    return Facility::whereNotNUll('id')->with('rates')->get();
    

    which orders automaticaly orders the rates relationship

    the actual sub-query for the with method would look like this

    SELECT * 
    FROM rates
    INNER JOIN rate_types
    ON rate_types.id = rates.rate_type_id
    WHERE rates.facility_id in (ids of loaded facilities) 
    ORDER BY rate_types.weight
    ASC
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search