Yii2按关系排序

时间:2015-05-08 01:27:58

标签: php mysql sql yii yii2

我有以下数据库:

day: id
task: id
day_task: day_id, task_id, 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]);
    });
}

导致:

SELECT * FROM `day_task` WHERE `day_id`=2 ORDER BY `weight`
SELECT * FROM `task` WHERE `id` IN ('2', '1', '3', '4')

问题是DBMS返回存储在表中的行而不考虑IN的顺序,所以我得到'1','2','3','4'而不是'2' ,'1','3','4'。

除了手动逐行取出之外,我找不到任何解决方案。

2 个答案:

答案 0 :(得分:1)

尝试在结束查询中添加orderBy

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

答案 1 :(得分:0)

我没有测试过这个:

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

这应该会导致如下查询:

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

这是真的吗?