【发布时间】:2023-03-14 16:40:01
【问题描述】:
我喜欢这个模型:
class Post extends Model
{
use HasFactory;
protected $guarded = [];
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
public function views()
{
return $this->morphMany(View::class, 'viewable');
}
public function category()
{
return $this->belongsTo(Category::class);
}
}
通过这个查询我会得到帖子:
$posts = Post::query()
->with([
'category',
'images',
])
->withCount([
'views'
])
->get();
问题:
如何汇总帖子浏览量并按类别分组以获得每个类别的总浏览量?
我可以使用这样的原始 SQL 查询获得所需的结果:
SELECT `categories`.`title` AS `category`,
COUNT(`views`.`viewable_id`) AS `totalViews`
FROM `posts`
LEFT JOIN `categories`
ON `categories`.`id` = `posts`.`category_id`
LEFT JOIN `views`
ON `views`.`viewable_id` = `posts`.`id`
WHERE `views`.`viewable_type` = "App\\Models\\Post"
GROUP BY `categories`.`id`
但是如何使用 laravel eloquent 生成这样的 sql 查询并获得结果呢?
【问题讨论】:
标签: php laravel eloquent relationship laravel-8