Yii2 Relationship Order

I have the following database:

day: id
task: id
day_task: day_id, task_id, weight

Now I want to get all the tasks from a specific day, sorted 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]);
    });
}

Result:

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 rows because they were stored in the table, not taking into account the order of IN, and therefore I get "1", "2", "3", "4" instead of "2", '1', '3', '4'.

I could not find any solution, except that he manually picked the rows in a row.

+4
source share
2 answers

try adding orderBy at the end of the request

public function getTasks()
{
   return $this->hasMany(Task::className(), ['id' => 'task_id'])- >viaTable('day_task', ['day_id' => 'id'])->orderBy(['weight' => SORT_ASC];
}
+1
source

I have not 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 trigger 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

It's true?

0
source

All Articles