【问题标题】:Laravel 5.7 - Get all users from current user groupsLaravel 5.7 - 从当前用户组中获取所有用户
【发布时间】:2019-06-27 07:58:18
【问题描述】:

这是我目前使用的结构

模型用户:

class User extends Authenticatable implements MustVerifyEmail


public function groups()
{
    return $this->belongsToMany('App\Group')
        ->withTimestamps();
}

模型组:

class Group extends Model

public function users() {
    return $this->belongsToMany('App\User')
        ->withTimestamps();
}

数据透视表:

    Schema::create('group_user', function (Blueprint $table) {
        $table->integer('group_id');
        $table->integer('user_id');
        $table->integer('role_id')->nullable();
        $table->timestamps();
    });

我想获取当前用户的同一组中的所有用户并且不返回重复用户(一个用户可以在多个组中)。 理想的功能是:

$user->contacts()
// Return an object with (unique) contacts of all current user groups

AND

$user->groupContacts($group)
// Witch is the same as $group->users
// Return an object with all the users of the current group

我正在处理的不是功能性功能(Model User.php):

    public function contacts()
{

    $groups = $this->groups;
    $contacts = new \stdClass();

    foreach ($groups as $key => $group) :

        $contacts->$key = $group->users;

    endforeach;

    return $contacts;

}

我真的不是表格结构方面的专家,所以如果有更好的方法来做到这一点,我只是在这个个人项目的开始,所以没有什么是一成不变的。

可选的东西:

  • 从列表中排除当前用户
  • 使用数据透视表中的角色
  • 带软删除

【问题讨论】:

    标签: php laravel-5 eloquent pivot-table eloquent-relationship


    【解决方案1】:

    你可以在你的用户模型上尝试这样的事情

    public function contacts()
    {
        // Get all groups of current user
        $groups = $this->groups()->pluck('group_id', 'group_id');
        // Get a collection of all users with the same groups
        return $this->getContactsOfGroups($groups);
    }
    
    public function groupContacts($group)
    {
        // Get a collection of the contacts of the same group
        return $this->getContactsOfGroups($group);
    }
    
    
    public function getContactsOfGroups($groups)
    {
        $groups = is_array($groups) ? $groups : [$groups];
        // This will return a Collection Of Users that have $groups
        return \App\User::whereHas('groups', function($query) use($groups){
            $query->whereIn('group_id', $groups);
        })->get();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 1970-01-01
      • 2014-08-28
      • 2015-09-06
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      相关资源
      最近更新 更多