'Yii2 Order By Relations
I have the following database:
day: id
task: id
day_task: day_id, task_id, weight
Now I want to fetch all tasks from a specific day ordered by weight.
public function getTasks()
{
return $this->hasMany(Task::className(), ['id' => 'task_id'])->viaTable('day_task', ['day_id' => 'id'], function ($query) {
$query->orderBy(['weight' => SORT_ASC]);
});
}
Resulting in:
SELECT * FROM `day_task` WHERE `day_id`=2 ORDER BY `weight`
SELECT * FROM `task` WHERE `id` IN ('2', '1', '3', '4')
The problem is that the DBMS returns the rows as they were stored in the table not considering the order of the IN and so I get '1', '2', '3', '4' instead of '2', '1', '3', '4'.
I could not find any solution apart from fetching it manually row by row.
Solution 1:[1]
try add orderBy at the end query
public function getTasks()
{
return $this->hasMany(Task::className(), ['id' => 'task_id'])
->viaTable('day_task', ['day_id' => 'id'])
->orderBy(['weight' => SORT_ASC]);
}
Solution 2:[2]
I didn't tested this:
// in class Day:
public function getTasks() {
return Task::find()
->leftJoin('day_task', 'task.id=day_task.task_id')
->where(['day_task.day_id' => $this->id])
->orderBy(['day_task.weight' => SORT_ASC]);
}
This should cause a query like:
SELECT task.*
FROM task LEFT JOIN day_task ON task.id = day_task.task_id
WHERE day_task.day_id = <id_of_day>
ORDER BY day_task.weight ASC
Is this true?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | robsch |
| Solution 2 | robsch |
