【问题标题】:Count from hasManyThrough relationship with eager loading (need only Count)从 hasManyThrough 关系中计数与急切加载(只需要计数)
【发布时间】:2018-04-28 16:41:43
【问题描述】:

我只需要计数,不想每次都检索结果或执行查询。这就是我想要急切加载的原因。

我有 3 个如下表:

Admins
    id

Posts
    id
    admin_id

Comments
    id
    user_id    //nullable (null if comment from admin)
    admin_id   //nullable (null if comment from user)
    news_id

现在我想从一个管理员那里检索所有帖子,并从这些帖子中计算所有 cmets,而不检索所有帖子的 cmets,仅计算 cmets, 急切加载以避免 n+1 查询问题;

在这里,我认为我们应该建立一个关系以用于急切加载,如下所示:

//admin model    
public function commentsCountRelation()
        {
            return $this->hasManyThrough(Comment::class, News::class, 'admin_id', 'news_id')
                ->selectRaw('news_id, count(*) as count')
                ->groupBy('news_id');
            
        }

--看这里我使用了hasManyThrough 关系,因为news_id 不在Admins 表中。

然后我应该创建一个属性,以便轻松访问计数,例如:

public function getCommentsCountAttribute()
    {   
        return $this->commentsCountRelation->first()->count ?? 0;
    }

然后像这样访问它:

$admin = Admin::with('commentsCountRelation')->findOrFail($id);
$admin->commentsCount;

但它总是返回null,这是为什么呢?

以下适用于hasManybelongsTo,我在其他型号上使用过,例如:

//relation
public function ordersCountRelation()
    {
        return $this->hasOne(Order::class)->selectRaw('user_id, count(*) as count')
            ->groupBy('user_id');
        
    }

//attribute
public function getOrdersCountAttribute()
    {
        return $this->ordersCountRelation->count ?? 0;
    }

//Then accessed like:
$user = User::with('ordersCountRelation')->find($id);
$user->ordersCount; //return only count

我们将不胜感激任何帮助

【问题讨论】:

    标签: laravel count eloquent has-many-through eager-loading


    【解决方案1】:

    没有必要使用hasManyThrough
    只需使用一些关系和withCount 方法:

    $admin->posts->withCount('comments')->get();

    然后您可以通过以下方式访问它:$comments_count

    【讨论】:

    • 我不明白。该应用程序有多个管理员,所有管理员都有帖子。现在我需要来自特定管理员的所有帖子,所有的 cmets 只计算那些帖子,问题是我描述了表格结构,我在使用 Admin 模型时需要该评论计数,你能解释一下我该怎么做没有hasManyThrough,因为我不想获得所有帖子的计数,而只想获得来自该管理员的帖子。我需要这样(循环后)$admin->post->commentCount 如果你给我一些代码示例或简要解释,我将不胜感激
    • 关系:AdminhasManyPosthasManyComment
    • 我也认为您的方法没有使用急切加载,是吗?您能否告诉我使用您的提及方法而不是$admin->post->comments->count() 的效率优势是什么
    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 2016-01-08
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2021-04-28
    • 2020-11-09
    • 2015-03-20
    相关资源
    最近更新 更多