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.