首页 文章

使用数据透视表上的hasManyThrough检索相关模型 - Laravel 5.7

提问于
浏览
0

我正在尝试从数据透视表中检索相同类型的相关模型 .

我有2个型号, App\Models\UserApp\Models\Group 以及一个枢轴模型 App\Pivots\GroupUser

我的表格具有以下结构

用户

  • id

  • id

GROUP_USER

  • id

  • user_id

  • group_id

我目前将关系定义为

在app / Models / User.php中

public function groups()
{
    return $this->belongsToMany(Group::class)->using(GroupUser::class);
}

在app / Models / Group.php中

public function users()
{
    return $this->belongsToMany(User::class)->using(GroupUser::class);
}

在app / Pivots / GroupUser.php中

public function user()
{
    return $this->belongsTo(User::class);
}

public function group()
{
    return $this->belongsTo(Group::class);
}

我正在尝试在我的 User 类中定义一个关系,以通过位于同一组中来访问所有其他相关用户 . 叫它 friends . 到目前为止,我试过这个:

应用/型号/ user.php的

public function friends()
{
    return $this->hasManyThrough(
        User::class,
        GroupUser::class,
        'user_id',
        'id'
    );
}

但它最终只返回一个集合,只有我称之为关系的用户 . (与运行 collect($this); 相同

我有一个可行的解决方案,但并不理想 .

应用/型号/ user.php的

public function friends()
{
    $friends = collect();
    foreach($this->groups as $group) {
        foreach($group->users as $user) {
            if($friends->where('id', $user->id)->count() === 0) {
                $friends->push($user);
            }
        }
    }

    return $friends;
}

有没有办法使用 hasManyThrough 或其他一些Eloquent函数来完成这个?

谢谢 .

2 回答

  • 0

    你不能使用 hasManyThrough 这样做,因为 users 表上没有外键可以将它与 group_user 表的 id 相关联 . 你可以尝试使用现有的 belongsToMany 关系从用户到他们的团队到他们的朋友:

    应用程序/模型/ user.php的:

    // create a custom attribute accessor
    public function getFriendsAttribute()
    {
        $friends = $this->groups()                                          // query to groups
                        ->with(['users' => function($query) {               // eager-load users from groups
                            $query->where('users.id', '!=', $this->id);     // filter out current user, specify users.id to prevent ambiguity
                        }])->get()
                        ->pluck('users')->flatten();                        // massage the collection to get just the users
    
        return $friends;
    }
    

    然后,当您调用 $user->friends 时,您将获得与当前用户位于同一组中的用户集合 .

  • 0

    你试过Eager Loading吗?希望这有帮助 .

相关问题