我有Post模型,并且有:
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();
}
我需要在CONCAT(points, '_', created_at)
中添加一个reviews_count
,然后执行ORDER BY points desc, reviews_count desc, created_at asc
。属性reviews_count
在查询中不起作用。我需要添加子查询或联接。我该怎么做?我尝试过:
DB::statement("UPDATE posts set `rank` = (SELECT COUNT(*) FROM reviews WHERE post_id = posts_rankings.id) as reviews_count, (SELECT FIND_IN_SET( CONCAT(points, '_', reviews_count, '_', created_at), (SELECT GROUP_CONCAT( CONCAT(points, '_', reviews_count, '_' created_at) ORDER BY points desc, reviews_count desc, created_at asc ) FROM (select * from posts) as posts_rankings)))");
但这会让我出错:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'reviews_count