如何使用一对多关系在Laravel中保存选定的列表?

时间:2016-07-07 15:43:46

标签: php mysql laravel laravel-5.2

我在想如何在表用户中保存用户选择的列表?如果用户选择第一个选项,则值将插入我的role_id中,值为1,依此类推。

<div class = "form-group {{ $errors->has('role') ? ' has-error' : '' }}">

<label for = "role" class = "control-label">Role</label>

<select class = "form-control" name = "role">

    <option selected disabled>Please select role</option>
    <option value = "role1">Supplies Officer</option>
    <option value = "role2">Admin Officer</option>
    <option value = "role3">Attorney</option>
    <option value = "role4">Chairman</option>

</select>

 @if ($errors->has('role'))
    <span class = "help-block">{{ $errors->first('role') }}</span>
 @endif

示例SQL:

INSERT INTO `users`(`role_id`, `email`, `username`) VALUES (1,'francis@gmail.com','francis')

我有一个表角色用户表有一对多的关系。

enter image description here

角色表:我已经在这里插入了一个值。

roles Table

用户(型号)

class User extends Model implements AuthenticatableContract
{
use Authenticatable;

protected $table = 'users';

protected $fillable = [
    'username',
    'email',
    'password',
    'role_id',
];

public function role()
{
    return $this->belongsTo('Role');
}
}

角色(模型):

class Role extends Model
{
protected $table = 'roles';

public function user()
{
    return $this->hasMany('User');
}
}

控制器:

我仍然不知道如何插入或保存所选列表。任何帮助将不胜感激!

public function postRegister(Request $request)
{
    $this->validate($request, [
                            //This will be unique in users table
        'email' => 'required|unique:users|email|max:255',
        'username' => 'required|unique:users|alpha|max:20',
        'password' => 'required|min:6',
        'role' => 'required',
    ]);

    $email = $request['email'];
    $username = $request['username'];
    $password = bcrypt($request['password']);
    $role = $request['role'];

    $user = new User();
    $user->email = $email; //Accessing properties of Model
    $user->username = $username;
    $user->password = $password;


    $user->save();

}

1 个答案:

答案 0 :(得分:0)

您已将role_id传递给User对象。

$user->role_id = 1;
$user->save();

现在您的角色已分配给您的用户。您可以检查SQL数据库或在$ user变量上创建一个dd()。

dd($user);

您可以使用eloquent进行分配,这是一种更好的方法。

$role = \Role::findOrFail($request['role_id']);
$role->user()->assign($user)->push(); // This ligne assign the id of the Role Model into the User Model automaticly.

在这种情况下,角色模型必须在用户模型上具有belongsTo关系。