是否可以在Laravel 5.2中通过链外键关系插入记录

时间:2016-07-24 18:08:44

标签: eloquent laravel-5.2

我有三个表/模型:用户员工 employee_disability

  1. 员工具有外键 user_id
  2. employee_disability 包含 emp_id 外键。
  3. 有没有办法执行以下操作:

    $user->employee()->empdisability()->create(['name'=>$name,'percent'=>$percent]);
    

    感谢任何帮助。提前谢谢。

    模型

    class user extends Authenticatable{
        public function employees(){
           return $this->hasMany('App\Models\employee','user_id');
        }
    }
    
    class employee extends Model{
        public function user(){
             return $this->belongsTo('App\Models\user','user_id');
        }
    
        public function empdisability(){
             return $this->hasMany('App\Models\emp_disability','emp_id');
        }        
    }
    
    class emp_disability extends Model{
        public function employee(){
            return $this->belongsTo('App\Models\employee','emp_id');
        }
    }
    

    CONTROLLER

    public function storeDisability(Request $request){
        $user=Auth::user();
        $name=$request->name; $percent=$request->percent;
        $user->employee()->empdisability()-  >create(['name'=>$name,'percent'=>$percent]);
    }
    

1 个答案:

答案 0 :(得分:0)

$user->employee()返回员工关系的查询构建器,但您需要的是实例。

这应该有效,请注意employee

上没有包袱
$user->employee->empdisability()->create(['name'=>$name,'percent'=>$percent]);