简体   繁体   English

Laravel计数Eloquent属于ToMany相关模型

[英]Laravel count Eloquent belongsToMany related model

I'm new to Laravel, and I got stuck with the following issue: I have a table for the users, and groups, and a table for connecting them. 我是Laravel的新手,我遇到了以下问题:我有一个用户表,组和一个用于连接它们的表。 The general task any user can join any group. 任何用户可以加入任何组的常规任务。

----------------------------------------------
| users        | groups     | user_groups    |
|--------------------------------------------|
| id - int pk  | id - pk    | id - pk        |
| name text    | name       | user_id - fk   |
| email        |            | group_id - fk  |
| phone        |            | any_attr       |
----------------------------------------------

I have the following models: 我有以下型号:

class User
{
    ...
    public function groups()
    {
        return $this->belongsToMany(Group::class, 'user_groups')->withPivot(['is_notification_requested']);
    }
    ...
}


class Group
{
    ...
    public function users()
    {
        return $this->belongsToMany(User::class, 'user_groups');
    }
    ...
}

How do I get all of the groups, with a count of the members? 我如何获得所有成员的数量? I need the Group model, and a count of the users in the group. 我需要Group模型,以及组中用户的计数。

If you're using Laravel 5.3, you can simply add withCount('relationship') as documented here: https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models 如果您使用的是Laravel 5.3,您只需添加withCount('relationship')如下所示: https ://laravel.com/docs/5.3/eloquent-relationships#counting-related-models

Here's an example following your code: 以下是您的代码后面的示例:

$groups = Group::withCount('users')->get();

Now you can do this: 现在你可以这样做:

foreach($groups as $group) {
    echo $group->user_count
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM