duanduanxi9441 2019-05-10 06:26
浏览 333

获取同一组中所有用户的数据

My code works. But I'm not sure is it a best solution. I need option to display user players and / or players from a group user belong to. Thank you for you time.


$user = $request->user();
$userGroups = $user->groups;
$friendsPlayers = [];

foreach ($userGroups as $group) {

    $groupUsers = $group->users;

    foreach ($groupUsers as $groupUser) {

        if ($groupUser->id !== $user->id) {

            $userPlayer = $groupUser->players;

            foreach ($userPlayer as $player) {

                if (!in_array($player, $friendsPlayers)) {

                    $friendsPlayers[] = $player;
                }
            }
        }
    }
}

1.Schema/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 Schema::create('groups', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('info');
        $table->timestamps();
    });

 Schema::create('players', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->index();
        $table->string('name');
        $table->string('url');
        $table->string('type');
        $table->integer('wins');
        $table->integer('lost');
        $table->integer('draws');
        $table->timestamps();
    });

   Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
 Schema::create('group_user', function (Blueprint $table) {

        $table->integer('group_id')->unsigned()->nullable();
        $table->foreign('group_id')->references('id')
              ->on('groups')->onDelete('cascade');

        $table->integer('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')
              ->on('users')->onDelete('cascade');
        $table->timestamps();
    });

2.Models/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 class Group extends Model
 {
 protected $fillable = [
    'name', 'info',
 ];
 public function users() {
    return $this->belongsToMany(User::class);
 }
 }


 class Player extends Model
 {   
 protected $guarded = [];


public function user() {
        return $this->belongsTo(User::class);
}
public function leagues() {
    return $this->belongsToMany(League::class)->withPivot('win', 'lost', 
'draw')->withTimestamps();
}


class User extends Authenticatable
{
use Notifiable;


protected $fillable = [
    'name', 'email', 'password',
];


protected $hidden = [
    'password', 'remember_token',
];
public function players() {
    return $this->hasMany(Player::class);
}
public function leagues() {
    return $this->hasMany(League::class);
}
 public function scoreboards() {
    return $this->hasMany(Scoreboard::class);
 }
 public function groups() {
    return $this->belongsToMany(Group::class);
 }
 }
  • 写回答

1条回答 默认 最新

  • drvntaomy06331839 2019-05-10 07:14
    关注

    This could be a perfect use case to use Laravel Collection.

    $result = $user->load('groups.groupUsers.players')
        ->groups
        ->map->groupUsers
        ->collapse()
        ->filter(function ($groupUser) use ($user) {
            return $groupUser->isNot($user);
        })
        ->unique('id')
        ->map->players
        ->collapse()
        ->unique('id');
    

    A different approach is using a query to get the result.

    First, lets create a sub query to get all the groups the user joined.

    $groupsJoinedByUser = Group::whereHas('users', function ($query) use ($user) {
        $query->whereKey($user->id);
    });
    

    We can also create that sub-query this way:

    $groupsJoinedByUser = Group::select('groups.*')
        ->join('group_user', 'groups.id', '=', 'group_user.group_id')
        ->where('group_user.user_id', $user->id);
    

    Now we can create the query to get the players:

    $players = Player::select('players.*')
        ->join('users', 'players.user_id', '=', 'users.id')
        ->join('group_user', 'users.id', '=', 'group_user.user_id')
        ->joinSub($groupsJoinsByUser, 'groups_joined_by_user', function($join) {
            $join->on('group_user.group_id', '=', 'groups_joined_by_user.id')
        })
        ->where('users.id', '!=', $user->id);
        ->distinct()
        ->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?