【问题标题】:Retrieve related models using hasManyThrough on a pivot table - Laravel 5.7在数据透视表上使用 hasManyThrough 检索相关模型 - Laravel 5.7
【发布时间】:2018-11-01 01:04:13
【问题描述】:

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

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

我的表具有以下结构

用户

  • 身份证

  • 身份证

组用户

  • 身份证
  • 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。到目前为止,我已经尝试过:

app/Models/User.php

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

但它最终只会返回一个集合,其中只有我调用关系的用户。 (与运行collect($this); 相同

我有一个可行但不理想的解决方案。

app/Models/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 函数来完成此任务?

谢谢。

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-5.7


    【解决方案1】:

    您无法使用 hasManyThrough 执行此操作,因为 users 表上没有外键可将其与 group_user 表的 id 相关联。您可以尝试使用现有的belongsToMany 关系从用户到他们的组再到他们的朋友:

    app/Models/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你会得到与当前用户在同一组的用户集合。

    【讨论】:

      猜你喜欢
      • 2015-09-10
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2019-04-17
      相关资源
      最近更新 更多