[英]unable to make the foreign key get its referenced id value by default
I am new in LARAVEL and i got some issues. 我是LARAVEL的新手,我遇到了一些问题。
My problem is that when i insert data into the first table i can see that it has an id settled by default but when i insert data into the second table i keep getting this error : 我的问题是,当我将数据插入第一个表时,我可以看到它有一个默认设置的ID但是当我将数据插入第二个表时,我不断收到此错误:
SQLSTATE[HY000]: General error: 1364 Field 'etudiant_id' doesn't have a default value SQLSTATE [HY000]:常规错误:1364字段'etudiant_id'没有默认值
What should i do to give the foreign key the id number of the first table? 如何为外键提供第一个表的id号?
Here is my Schemas : 这是我的架构:
the first table -etudiant- : 第一个表-etudiant-:
public function up()
{
Schema::create('etudiants', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->timestamps();
});
}
the second table -bac2- : 第二个表-bac2-:
public function up()
{
Schema::create('bac2', function (Blueprint $table) {
$table->increments('id');
$table->integer('etudiant_id')->unsigned();
$table->foreign('etudiant_id')->references('id')->on('etudiants')-
>onDelete('cascade') ;
$table->date('anne_bac2');
$table->timestamps();
});
}
Here is my insertion function : 这是我的插入功能:
function insert(Request $req){
$nom = $req->input('name');
$data= array('nom'=>$nom);
$anne_bac2 = $req->input('anne_bac2');
$data2= array('anne_bac2'=>$anne_bac2);
DB::table('etudiants')->insert($data);
DB::table('bac2')->insert($data2);
return "success";
}
You need to add foreign key to the data you're trying to insert. 您需要将外键添加到您尝试插入的数据中。 So, change these lines: 所以,改变这些线:
$data2= array('anne_bac2'=>$anne_bac2);
DB::table('etudiants')->insert($data);
DB::table('bac2')->insert($data2);
To: 至:
$etudiantId = DB::table('etudiants')->insertGetId($data);
$data2 = ['anne_bac2' => $anne_bac2, 'etudiant_id' => $etudiantId];
DB::table('bac2')->insert($data2);
Or better refactor whole method: 或者更好的重构整个方法:
function insert(Request $request)
{
$etudiantId = DB::table('etudiants')->insertGetId(['nom' => $request->name]);
DB::table('bac2')->insert(['anne_bac2' => $request->anne_bac2, 'etudiant_id' => $etudiantId]);
return "success";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.