douan8473 2019-02-03 09:28 采纳率: 100%
浏览 7
已采纳

too long

This this the structure that I currently use

Model User :

class User extends Authenticatable implements MustVerifyEmail


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

Model Group :

class Group extends Model

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

Pivot table :

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

I would like to get all the users who are in same groups of the current user and don't return duplicate users (a user can be in multiple groups). The ideal functions would be :

$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

There is the not functional function i'm working on (Model User.php) :

    public function contacts()
{

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

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

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

    endforeach;

    return $contacts;

}

I'm really not an expert with table structures so if there is a better way to do this, i'm only at the beginning of this personnal project so nothing is written in stone.

Optional stuffs :

  • Exclude current user from the list
  • With roles from pivot table
  • With softdelete
  • 写回答

1条回答 默认 最新

  • dongyi9023 2019-02-03 11:35
    关注

    You can try something like this on your User model

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?