如何在db中存储模型之间的关系? - Laravel

时间:2016-09-28 10:39:51

标签: eloquent laravel-5.2 relationships

我有一个员工表和一个角色表。在创建员工的过程中,我也希望分配一个角色。但是,我的代码在employees表的外键中存储NULL数据。如何使其存储关系?

员工model.php

 class employees extends Model
{
     protected $fillable = [
     'first_name',
     'surname',
     ];

    public function Roles()
    {
        return $this->belongsTo('App\Roles');
    }

Roles model.php

class Roles extends Model
{
    protected $fillable = [
    'role_name',
    ];

    public function Employees()
    {
   return $this->hasMany('App\Employees');
    }
}`

创建员工的控制器

 public function store(EmployeesRequest $request)
{
     $employee = Employees::find($request); 
    Employees::create($request->all());
    Roles::create($request->all());
    $employee->roles()->save($roles);
    return redirect()->route('employees.index')->with('message','Employee has been added'); 

}

在表单上我有first_name,surname和role_name。这些已保存,但在employees表的role_id列中为NULL?尝试阅读laravel文档,但努力使用 - >保存方法

它返回的当前错误是在null

上调用成员函数roles()

1 个答案:

答案 0 :(得分:0)

您必须在您的员工模型中填写role_id:

protected $fillable = [
     'role_id', 
     'first_name',
     'surname',
     ];

在您的控制器中: 您需要使用App \ Roles;

public function create()
    {   
        $role = Role::lists('role_name', 'id'); 
        return view('roles.create', compact('role'));

    }

 public function store(EmployeesRequest $request)
    { 
        Employees::create($request->all());
        return redirect()->route('employees.index')->with('message','Employee has been added'); 
    }

形式:

<div class="form-group">
            {!! Form::label('role_id', 'Role:') !!}
            {!! Form::select('role_id', $role, null, ['class' => 'form-control']) !!}
        </div>

HTML表格: 尝试这样的东西,我希望它的工作原理没有经过测试

<label>Role</label>
<select name="role_id">
  @foreach($roles as $role)
    <option value="{{ $role->id }}">{{ $role->role_name }}</option>
  @endforeach
</select

在您的控制器中:

public function create()
    {   
        $roles = Role::all();    
        return view('roles.create', compact('roles'));

    }