【问题标题】:Laravel count Eloquent belongsToMany related modelLaravel count Eloquent belongsToMany 相关模型
【发布时间】:2017-02-04 04:53:46
【问题描述】:

我是 Laravel 新手,遇到以下问题: 我有一个用于用户和组的表,以及一个用于连接它们的表。任何用户都可以加入任何组的一般任务。

----------------------------------------------
| 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');
    }
    ...
}

如何获取所有组以及成员数?我需要 Group 模型,以及组中的用户数。

【问题讨论】:

  • 是否需要将计数作为返回对象的先前计算的属性,还是可以在打印值时计算?
  • 你使用的是 Laravel 5.2 还是 5.3?
  • Laerte: 好吧,我什么时候得到价值没关系。我只需要一个组列表,以及组中用户的数量。它是一个分页列表。 Ollieread: Laravel 5.3

标签: php mysql laravel eloquent relationship


【解决方案1】:

如果您使用的是 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
}

【讨论】:

  • 我不知道这个。当然,这是一个更好的解决方案。
  • 这是 5.3 的新功能。
  • 两者都工作正常! :) 但我想我应该使用 withCount 方式。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 2021-07-07
  • 2018-08-10
  • 2013-06-10
  • 2014-11-25
  • 2016-02-26
  • 2015-10-23
相关资源
最近更新 更多