Reputation: 3321
I have a Objective model which has many Action and every Action has one ActionYear. already defined in model.
How to use orderby to sort action in objective through action_year's specific column.
$query = Objective::with('actions.actionYear')
->orderBy('action_year.created_at')
->get();
this through error Undefined table: 7 ERROR: missing FROM-clause entry for table "action_year"
.
How to solve this. Thank you.
Upvotes: 0
Views: 2759
Reputation: 153010
You can order the eager loaded models with a closure:
$query = Objective::with(['actions.actionYear' => function($q){
$q->orderBy('action_year.created_at');
})->get();
Upvotes: 0
Reputation: 8663
If you use function with() then this only makes sure the named relationship is loaded also to avoid extra need for SQL queries later. Othewise it does not introduce any additional changes compared to Objective::all()
One way how to achieve sorted collection is to use sortBy()
function after loading the data like this
$query = $query->sortBy(function($objective){
return $objective->actionYear->created_at;
});
Upvotes: 0