【问题标题】:Adding data to a pivot table while inserting a new record using select option Laravel 5.2使用选择选项 Laravel 5.2 在插入新记录时将数据添加到数据透视表
【发布时间】:2017-05-09 10:55:03
【问题描述】:

那么问题来了:

我创建了一个 CRUD 系统,以便管理员可以创建/读取/更新/删除用户。 问题是我无法在我的 CRUD 系统中为用户选择角色。任何帮助将不胜感激!

我将指出我正在使用的 3 个迁移:用户、角色和他们的数据透视表 user_role。

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

Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('name', 40);
        $table->string('description', 255);
    });

Schema::create('user_role', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->integer('user_id');
        $table->integer('role_id');
    });

这是在我的用户模型中:

public function roles(){
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

这是我的榜样:

public function users(){
    return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}

我像这样在 RoleTableSeeder 中播种一些角色:

Role::create([
        'id'            => 1,
        'name'          => 'Admin',
        'description'   => 'Admin User.'
    ]);
    Role::create([
        'id'            => 2,
        'name'          => 'Vendor',
        'description'   => 'Vendor User.'
    ]);
    Role::create([
        'id'            => 3,
        'name'          => 'User',
        'description'   => 'Simple User.'
    ]);

这是创建用户的代码:

        {!! Form::open(['route' => 'admin.users.allusers']) !!}
        <div class="form-group">
            {!! Form::label('Username', 'Username:') !!}
            {!! Form::text('username',null,['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('E-mail', 'E-mail:') !!}
            {!! Form::text('email',null,['class'=>'form-control']) !!}
        </div>
        <div class="form-group">
            {!! Form::label('Role', 'Role:') !!}
            <select class="form-control" id="role" name="role">
                <option value="Administrator">Administrator</option>
                <option value="Vendor">Vendor</option>
                <option value="User" selected="selected">User</option>
            </select>
        </div>
        <div class="form-group">
            {!! Form::submit('Create', ['class' => 'btn btn-primary']) !!}
            <a href="{{ route('admin.users.allusers')}}" class="btn btn-primary">Back</a>
        </div>
        {!! Form::close() !!}

【问题讨论】:

  • 为什么角色-用户关系是多对多的?您似乎只允许用户在该行中分配一个角色。您可以发布处理表单的控制器代码吗?
  • role_user 是多对多关系,因为我认为可以有很多用户具有相同的角色,反之亦然。
  • public function store(Request $request){ $user=Request::all(); User::create($user); return redirect()-&gt;back(); }

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

创建用户后,您需要显式初始化 roles 关系。

$user = User::create(Request::all()); //user needs to be saved first so that ID is known
$role = Role::whereName(Request::input('role'))->first();
$user->roles()->attach($role);

【讨论】:

  • 它还需要别的东西吗?我在我之前向您展示过的控制器上尝试过,现在我得到了:Handler.php 第 103 行中的 NotFoundHttpException:模型 [App\Role] 没有查询结果。 Builder.php 第 209 行中的 ModelNotFoundException:没有模型 [App\Role] 的查询结果。
  • 哦,我没有注意到您在选择下拉列表中使用角色名称,而不是 ID。我已经更新了答案。您的应用中可能存在另一个错误:在选择中您使用值为“Administrator”的角色,但数据库中的名称为“Admin”
  • 现在它似乎有这个问题: AdminUserController.php 中的 FatalErrorException 第 31 行:调用数组上的成员函数角色()第 31 行:$user->roles()->attach($角色);
  • 您是否对代码进行了任何更改? $user 变量应该存储创建的用户对象。我已经更新了第一行。如果问题仍然存在,您能否执行 dd($user) 并告诉我您看到了什么?
  • 好吧,我也像您一样编辑了第二行。我还将下拉列表中的值从管理员更改为管理员,以匹配我的数据库。我做了 dd($user)。这就是我得到的:array:4 [▼ "_token" =&gt; "M00hwGo1ZJPPFzdmOVtE4PVpfyPJQb6D3RLz6g4g" "username" =&gt; "asdf" "email" =&gt; "asdf" "role" =&gt; "User" ]
猜你喜欢
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
  • 2019-06-12
  • 2015-02-14
  • 1970-01-01
相关资源
最近更新 更多