Laravel count Eloquent belongsToMany 相关模型
Laravel count Eloquent belongsToMany related model
我是 Laravel 的新手,我遇到了以下问题:
我有一个 table 用于用户和组,还有一个 table 用于连接它们。一般任务任何用户都可以加入任何组。
----------------------------------------------
| users | groups | user_groups |
|--------------------------------------------|
| id - int pk | id - pk | id - pk |
| name text | name | user_id - fk |
| email | | group_id - fk |
| phone | | any_attr |
----------------------------------------------
我有以下型号:
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');
}
...
}
如何获取所有组以及成员数?我需要群组模型,以及群组中的用户数。
如果您使用的是 Laravel 5.3,您只需添加 withCount('relationship')
,如下所述:https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models
下面是您的代码示例:
$groups = Group::withCount('users')->get();
现在您可以这样做了:
foreach($groups as $group) {
echo $group->user_count
}
我是 Laravel 的新手,我遇到了以下问题: 我有一个 table 用于用户和组,还有一个 table 用于连接它们。一般任务任何用户都可以加入任何组。
----------------------------------------------
| users | groups | user_groups |
|--------------------------------------------|
| id - int pk | id - pk | id - pk |
| name text | name | user_id - fk |
| email | | group_id - fk |
| phone | | any_attr |
----------------------------------------------
我有以下型号:
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');
}
...
}
如何获取所有组以及成员数?我需要群组模型,以及群组中的用户数。
如果您使用的是 Laravel 5.3,您只需添加 withCount('relationship')
,如下所述:https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models
下面是您的代码示例:
$groups = Group::withCount('users')->get();
现在您可以这样做了:
foreach($groups as $group) {
echo $group->user_count
}