如何通过多对多关系正确访问元素?

问题描述 投票:0回答:1

数据库中有这样一个数据结构

模型用户:

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /*
      * Model(Users) with (Group_users)
      * users - group_users
        many-to-many
   */
    public function ingroup() {
        return $this->belongsToMany(Group_user::class, 'group_works');
    }

  
    /*
    * Model (users) with (Group_works)
        one-to-many
    */
    public function peoples() {
        return $this->hasMany(Group_works::class);
    }
}

型号组_用途:

class Group_user extends Model
{
    use HasFactory;

    protected $fillable = [
        'name_group',
        'user_id',
    ];

    /*
     * Model (Group_user) with (User)
     many-to-one
    */
    public function user() {
        return $this->belongsTo(User::class, 'user_id');
    }

    /*
    * Model (Group_user) with (User)
      many-to-many
    */
    public function ingroup() {
        return $this->belongsToMany(User::class, 'group_works');
    }

    /*
   * Model (Group_users) with (Group_works)
     one-to-many
   */
    public function peoples() {
        return $this->hasMany(Group_works::class);
    }

}

控制器代码:

// Editor group
    public function edit(Group_user $group, Request $request) {
        $editor = Auth::user()->id;
        $users = User::query()->get();
        return view('admin.groups.edit', compact('editor', 'group', 'users'));
    }

刀片管理.组.编辑:

Name group: {{ $group->name_group }}
Creator group: {{ $group->user->name }}

@foreach($users as $user)
  Code User: {{$user->id}}
  Name User: {{$user->name}}
  <?php if ($user->ingroup->id == $group->id) {?> User in a Group <?}?>
 @endforeach

结果出现错误:

此集合实例上不存在属性 [id]。

如何使用所提供的关联正确检查用户是否属于某个组?

尝试通过现有链接连接模型。

php laravel relationship
1个回答
1
投票

您正在尝试访问用户集合($user->ingroup)的 id 属性。组内关系是多对多的,因此它返回用户的集合,而不是单个用户。

Name group: {{ $group->name_group }}
Creator group: {{ $group->user->name }}

@foreach($users as $user)
  Code User: {{$user->id}}
  Name User: {{$user->name}}
  <?php if ($user->ingroup->contains('id', $group->id)) {?> User in a Group <?}?>
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.