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
You need to try below code.
You can just join the table in your
rates
relationship from Facility model, which allows you to callorderBy
ororderByDesc
on anyrate_types
columne.i. (assumed standard column names use by your relationship)
Then you can do something like
which orders automaticaly orders the
rates
relationshipthe actual sub-query for the
with
method would look like this