【问题标题】:laravel eloquent: Get all groups for a memberlaravel eloquent:获取成员的所有组
【发布时间】:2020-01-15 00:02:55
【问题描述】:

我有 3 张桌子:

user: id,name

group: id,name,parent_id made with this) // 这是一个嵌套类别

members: id,user_id,group_id,admin

和group_member: group_id,member_id 我想为一个成员获取所有组(包括子组)。是否可以通过 laravel 实现?

组模式:

  public function parent()
  {
    $parent =  $this->belongsTo('App\Group',  'parent_id');
    return $parent;
  }

  public function children()
  {
    $children = $this->hasMany('App\Group',  'parent_id');
    //$children->wherePublish(1);
    return $children;
  }



  public function members()
  {
      return $this->hasMany(Member::class);
  }

  public function member()
  {
      return $this->belongsToMany(Member::class);
  }

和会员模型:

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

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

和用户模型:

public function members()
{
    return $this->hasMany(Member::class);
}

我想要这样的东西(返回所有相关组):

auth()->user()->members()->groups()->get();

我收到了这个错误:

"调用未定义的方法 Illuminate\Database\Eloquent\Relations\HasMany::groups()"

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    请使用以下查询:

     App/User::where('id',auth()->user()->id)->with('members.groups')->get();
    

    【讨论】:

    • 谢谢。但它会返回用户。我想要组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    相关资源
    最近更新 更多