【问题标题】:Yii2: how to order activeRecord relation query by related field?Yii2:如何按相关字段排序activeRecord关系查询?
【发布时间】:2017-08-11 10:20:15
【问题描述】:

我想执行这个查询:

$topics = ForumTopic::find()
            ->with([                
                'lastPost' => function($query) {
                    $query->select(['id', 'ctime']);
                },
            ])
            ->orderBy('lastPost.ctime DESC')
            ->all();

在 ForumTopic 中声明的关系如下:

public function getLastPost()
{
    return $this->hasOne(ForumPost::className(), ['id' => 'lastPostId']);
}

但我的查询失败(因为 yii2 将所有查询分开并且不连接表)。 yii2 activeRecord有什么方法可以实现我的目的吗?

【问题讨论】:

    标签: activerecord yii2 yii2-model


    【解决方案1】:

    试试这个:

    $topics = ForumTopic::find()
            ->with([                
                'lastPost' => function($query) {
                    $query->select(['id', 'ctime']);
                },
            ])
            ->orderBy([ForumPost::tableName() . '.ctime' => SORT_DESC])
            ->all();
    

    【讨论】:

    • lastPostIdForumTopic 模型(不是 ForumPost)的字段。这实际上是在关系声明中提到的(这在指南中有所描述:An easy rule to remember this is, as you see in the example above, you write the column that belongs to the related Active Record directly next to it.)。
    • 那么如何帮助在 lastPost 关系选择中检索lastPostId
    • 对不起,我的回答太仓促了,我已经更新了,现在试试。
    • 这也没有解决。异常告诉Column not found: 1054 Unknown column 'forum_post.ctime' in 'order clause' The SQL being executed was: SELECT * FROM forum_topic ORDER BY forum_post.ctime 正如我在问题中提到的,主要问题是 yii2 activeRecord 不会在急切加载中加入表(它会进行单独的查询)。 (在 yii1 中它做到了。)
    • 试试joinWith,而不是with
    【解决方案2】:

    所以,为了澄清,正确的答案是:

    $topics = ForumTopic::find()
                ->alias('t')
                ->select(['t.*','l.ctime lastPostCtime'])
                ->joinWith([
                    'lastPost l' => function($query) {
                        $query->select(['l.id', 'l.ctime', 'l.userId', 'l.guestName']);
                    },
                ])
                ->orderBy('lastPostCtime DESC')
                ->all();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多