在迁移表中:
Schema::create('passws', function (Blueprint $table) {
$table->increments('id');
$table->integer('regist_id')->unsigned()->nullable();
$table->foreign('regist_id')->references('id')->on('regists');
$table->string('age');
$table->timestamps();
});
}
注册模型 - 定义的质量分配。
public function pass(){
return $this->hasOne('App\Passw');
}
在控制器中
$name = $request->name;
$task = Regist::whereName($name)->get();
foreach ($task as $tasks){
$passw1->regist_id = $tasks->id;
}
$passw1->age = $request->age;
$regist = new Regist();
$regist->pass()->save($passw1);
当我存储数据时,只存储了age,但regist_id存储为null,(没有错误消息或什么都没有)。在这里我确定控制器显示"regist_id" => 1
和"age" => 25
当我使用dd($passw1);
regist_id只是没有在DB表中获得商店。
我在哪里做错?
试试这个
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
如果Regist
有多个$name
,请试试这个
$regists = Regist::whereName($name)->get(); //it will give you a collection of Regist model
foreach ($regists as $regist){
$regist->pass()->create([
'age' => $request->age
]);
}
在这里检查文件https://laravel.com/docs/5.6/eloquent-relationships#the-create-method