This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Hi I have a car leasing plugin i have written. each car has multiple contracts which has a relationship defined in my model as hasMany
public $hasMany = [
'contracts' => ['TimMarner\Carleasing\Models\Contract']
];
Now every contract has a monthly rental price field. i want to be able to list vehicles by the cheapest monthly rental price in the contract table.
Is there a way to order my vehicle list by the contracts monthly_price.
thanks
oh nice !! it seems that it is what i am looking for ! :) Where did you put this code please ?
Hi Chris
just apply it after you where clause.
$model->where(....)->orderByRaw('sort_field IS NULL, sort_field ASC');
I had forgotten how to do this and had to remember the other day, so in case anybody else stumbles on this post, this is how I did it.
Let's assume: Model Students belongs to model Classroom If you are using YAML to do your relation field in a form... you would have something like:
models/student/fields.yaml
fields:
classroom:
label: 'Classroom Student bleongs to'
nameFrom: class_name
span: auto
type: relation
scope: sortedClassrooms
other_fields.....
The trick here is the SCOPE We set this scope on our classroom model:
class Calssrom extends model
{
// ... all your code with rules and whatnot
public function scopeSortedClassrooms($query){
return $query->orderBy('class_name', 'ASC');
}
That should do the trick.
(An observation, scopes allow you to do all sorts of cool things, like, if you have a "is_published" flag, you could filter only the published classrooms, or add any other logic to your relation)
1-7 of 7