Yii Missing attribute when using join() + one()

Viewed 24

I don't know if this is correct behavior of Yii Active Record, consider I have this code

$post = Post::find()
    ->alias('p')
    ->select(['p.*', 'COUNT(c.id) AS comment_count'])
    ->join('LEFT JOIN', 'comments c', 'p.id = c.post_id')
    ->groupBy('p.id')
    ->one();

I cannot access $post->comment_count, but when I use ->asArray()->one, I can access $post['comment_count'], is it possible to return as Post model while having access to comment_count? As this can be used for validation, example

// $post from code above
if ($post->comment_count != 0) {
    throw new UnprocessableEntityHttpException('Cannot delete post with comment(s)');
}

return $post->delete();
1 Answers

You need to add $comment_count inside the Post model, for example:

class Post {
    public $comment_count;

    .....
    public function attributeLabels()
    {
        return [
            'comment_count' => 'Total Comment',
            .....
        ]
    }

But if you are satisfied with asArray() as what you mentioned earlier, I think that is enough because it's pretty faster.

Related