【问题标题】:Yii2: How to use another query in orderByYii2:如何在 orderBy 中使用另一个查询
【发布时间】:2023-02-11 02:36:57
【问题描述】:

我创建了 fc_forum_post 表,当此列等于 1 时,其中一列是 is_question 表示该行是问题当列等于 0 时,表示该行是答案。

现在我想用 status = 2 ether question 或 'answer' 对我的网格视图进行排序。

事实上,我想用另一个查询对查询进行排序。 是这样的:

$query = ForumPost::find() ->select([ 'forum_post.*', 'waiting' => ForumPost::find() ->select('COUNT(*)') ->where('forum_post.is_question = 0') ->andWhere('forum_post.status = 2') ]) ->joinWith(['category', 'user']) ->where(['forum_post.is_question' => 1]) ->orderBy([ 'waiting' => SORT_DESC 'forum_post.status' => SORT_DESC ]);

我已经为我尝试过这个查询网格视图.实际上,我想让answer count 列与该列一起排序。

question title answer count
title one 4
title twho 3

**问题标题** = forum_post.is_question = 1 **答案计数** = forum_post.is_question = 0

如果您对更好地理解我的问题有任何疑问,请问我,我将不胜感激帮助我解决我的问题。

【问题讨论】:

    标签: php mysql yii2


    【解决方案1】:

    看起来您正在使用 Yii2 作为 PHP 框架,并且您正在尝试根据状态为 2 的答案计数 (forum_post.is_question = 0) 对网格视图进行排序。

    为此,您可以按如下方式修改查询:

    $query = ForumPost::find()
    ->select([
        'forum_post.*',
        'waiting' => (new Query())
            ->select('COUNT(*)')
            ->from(ForumPost::tableName())
            ->where(['is_question' => 0, 'status' => 2])
            ->andWhere(['parent_id' => new Expression('forum_post.id')])
    ])
    ->joinWith(['category', 'user'])
    ->where(['forum_post.is_question' => 1])
    ->groupBy('forum_post.id')
    ->orderBy([
        'waiting' => SORT_DESC,
        'forum_post.status' => SORT_DESC,
    ]);
    

    在上面的查询中,我们使用子查询来获取状态为 2 的答案的计数,然后按父问题 ID (forum_post.id) 对结果进行分组。最后,我们按降序排列 waiting 列和 forum_post.status 列对结果进行降序排列。

    这个查询应该给你你正在寻找的结果,网格视图根据状态为 2 的答案计数排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2022-01-07
      • 1970-01-01
      相关资源
      最近更新 更多