将外键值存储在 laravel 中
Store foreign key value in laravel
迁移中Table:
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);
当我存储数据时,只有年龄被存储但 regist_id 存储为 null,(没有错误消息或什么都没有)。在这里我确定控制器显示 "regist_id" => 1
和 "age" => 25
当我使用 dd($passw1);
regist_id 只是没有在 DB table.
中存储
我哪里出错了??
试试这个
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
如果 $name
有多个 Regist
,那么试试这个
$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
迁移中Table:
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);
当我存储数据时,只有年龄被存储但 regist_id 存储为 null,(没有错误消息或什么都没有)。在这里我确定控制器显示 "regist_id" => 1
和 "age" => 25
当我使用 dd($passw1);
regist_id 只是没有在 DB table.
我哪里出错了??
试试这个
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
如果 $name
有多个 Regist
,那么试试这个
$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