I’m encountering an issue with Laravel Eloquent while trying to order query results by a column from a related table. Specifically, I have a recipes table and a related nutrients table, and I want to order recipes by the kcal column in the nutrients table.
Here’s the code snippet I’m using:
$query = Recipe::with('nutrients');
// more code
if ($request->has('order_by')) {
$orderBy = $request->input('order_by');
$direction = $request->input('order_direction', 'asc');
// some code
elseif ($orderBy === 'kcal') {
if ($request->has('kcal')) {
$kcal = $request->input('kcal');
$query->whereHas('nutrients', function ($q) use ($kcal) {
$q->where('kcal', '<=', $kcal);
});
}
$query->orderBy('nutrients.kcal', $direction);
}
}
// some code
return RecipesResource::collection($recipes);
Models:
Recipe:
public function nutrients()
{
return $this->hasOne(Nutrient::class, 'recipe_id', 'id');
}
Nutrient:
public function recipe()
{
return $this->hasOne(Recipe::class);
}
However, this code is resulting in an SQL error: “Column not found: 1054 Unknown column ‘nutrients.kcal’ in ‘order clause'”. It seems like Laravel is not recognizing the kcal column in the nutrients table when trying to order the results.
I’ve tried different approaches, including explicitly specifying the table name in the orderBy clause, but so far, I haven’t been able to resolve the issue.
Can anyone provide insight into why this error is occurring and how to properly order query results by a column from a related table in Laravel Eloquent?
1