c1119
c1119

Reputation: 41

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.

Upvotes: 4

Views: 4320

Answers (2)

Đọc truyện hay
Đọc truyện hay

Reputation: 2023

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]);
}

Upvotes: 1

robsch
robsch

Reputation: 9728

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?

Upvotes: 0

Related Questions