【问题标题】:Laravel count morph many group by relationLaravel按关系计数变形许多组
【发布时间】: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


    【解决方案1】:

    您可以在 $posts 集合上使用 reduce。类似于:

    $categoriesCounts = $posts->reduce(static function(array $carry, Post $post) {
    
        $carry[$post->category_id] = ($carry[$post->category_id] ?? 0) + $post->views_count;
    
        return $carry;
    }, []);
      
    

    结果数组将如下所示:

    array(3) {
      [1] => int(4)
      [5] => int(20)
      [6] => int(10)
    }
    

    【讨论】:

    • 但是在我的情况下,我如何只使用没有 php 的 eloquent (sql) 才能得到这样的结果?我更新了我的问题,你可以看到我的原始查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2020-06-25
    • 2021-12-27
    • 2019-05-16
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多