【问题标题】:Sorting by joined data Yii2按连接数据排序 Yii2
【发布时间】:2016-06-30 13:01:19
【问题描述】:

在我的 Yii2 项目中,我有 postpost_views 表,以及一个 Post 模型。

post_views中有2个字段:

  • post_id
  • views_counter

我使用PostSearchPostsQuery (ActiveQuery) 进行查询。

我的任务是:我需要使用自定义字段views 获取我的所有帖子,其中我从post_views 获得views_counter

我没有在模型中使用hasMany,因为项目中没有post_views 表的模型,如果可能,我不想创建它。另外,我需要按views 字段对我的帖子进行排序。我被困在这个问题上:

public function topPosts(){
    $junction_table = '{{%post_views}}';
    return $this->innerJoin($junction_table, Post::tableName().'.id='.$junction_table.'.post_id');
}

主要问题是我不知道如何正确加入和返回数据。 我需要这个查询:

SELECT p.*, pv.views_count FROM posts p INNER JOIN post_views pv ON p.id = pv.post_id ORDER BY pv.views_count DESC;

【问题讨论】:

  • 只是出于好奇...我能问一下为什么views_counter 列不是post 表的一部分吗?我看不出有任何不存在的理由。
  • 我觉得以后可能会有更多的专栏所以我决定把它们分开

标签: php mysql yii2


【解决方案1】:

首先,您需要使用 viewCount 字段更新您的 Post 模型:

class Post extends \yii\db\ActiveRecord
{
    private $viewCount;

    public static function tableName()
    {
        return "posts";
    }

    public function setViewCount($viewCount)
    {
        $this->viewCount = $viewCount;
    }

    public function getViewCount()
    {
        return $this->viewCount;
    }
}

然后您需要在选择列表中包含 viewCount 字段,如下所示:

$post = new Post();
$query = $post->find()
        ->alias('p')
        ->select(['p.*', 'pv.views_count viewCount'])
        ->innerJoin("post_views pv", "p.Id = pv.id")
        ->limit(100)
        ->orderBy(["pv.views_count" => SORT_DESC]);

//Get SQL query string
echo $query->createCommand()->getSql();

//Execute query
$result = $query->all(); 

【讨论】:

猜你喜欢
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多