Dronax
8 months ago

Use accesor getAttribute in query model Laravel

Posted 8 months ago by Dronax

I have model Post, and I have:

protected $appends = ['reviews_count'];

public static function boot()
{
    parent::boot();

    static::saved(function () {
        static::updateRanks();
    });
}

public function reviews() {
   return $this->hasMany(Review:class);
}

public static function updateRanks()
{
    DB::statement("UPDATE posts set `rank` = (SELECT FIND_IN_SET( CONCAT(points, '_', created_at), (SELECT GROUP_CONCAT( CONCAT(points, '_', created_at) ORDER BY points desc, created_at asc ) FROM (select * from posts) as posts_rankings)))");
}

public function getReviewsCountAttribute()
{
    return $this->reviews()->active()->count();
}

I need in CONCAT(points, '_', created_at) add a reviews_count and next do ORDER BY points desc, reviews_count desc, created_at asc. How I can do this? If I add, I get error: unknown column reviews_count...

Please sign in or create an account to participate in this conversation.