按联接数据排序Yii2


Sorting by joined data Yii2

在我的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;

首先,您需要使用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();