所以我想知道如何将数据插入两个不同的表中,但链接到表Poste(offer,ad)和company,每个广告都链接到一个公司,我创建了两个Model,仅创建了一个Controller,Post and Company和后控制器。
Schema::create('entreprises', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nomEntreprise');
$table->string('adresseEntreprise');
$table->timestamps();
});
Schema::create('postes', function (Blueprint $table) {
$table->increments('idPoste');
$table->unsignedBigInteger('idEntreprise');
$table->string('nomPoste');
$table->text('descriptionPoste');
$table->timestamps();
$table->foreign('idEntreprise')
->references('id')
->on('entreprises')
->onDelete('cascade');
});
public function create()
{
$postes = Poste::all();
$entreprises = Entreprise::all();
return view('postes.create', compact('postes','entreprises'));
}
public function store(Request $request)
{
$data = $request->validate([
'nomPoste'=>'required|min:3',
'descriptionPoste'=>'required|min:3'
]);
$data2 = $request->validate([
'nomEntreprise'=>'required|min:3',
'adresseEntreprise'=>'required|min:3'
]);
Poste::create($data);
Entreprise::create($data2);
return back();
}
class Poste extends Model
{
protected $fillable = ['nomPoste','descriptionPoste','idEntreprise'];
public function entreprise()
{
return $this->belongsTo(Entreprise::class,'idEntreprise');
}
}
protected $fillable = ['nomEntreprise', 'adresseEntreprise'];
public function poste()
{
return $this->hasMany(Poste::class);
}
当我在工厂中插入数据时,效果很好,因为我设法通过ID与他的公司一起显示帖子。但是由于插入导致我出现以下错误:违反完整性约束:1452无法添加或更新子行:外键约束失败(projetetudiant.postes,CONSTRAINTpostes_identreprise_foreign FOREIGN KEY(idEntreprise)参考DELETE CASCADE上的企业(id)。
我是新手,只是到了Lurn laravel,而我已经被困住了,所以真的需要帮助!对不起,我的英语我是法国人。
如果没有企业记录,则无法插入帖子记录。就您而言,您要在企业之前插入帖子,这就是错误。
您的商店功能将变为:
public function store(Request $request)
{
$data = $request->validate([
'nomPoste'=>'required|min:3',
'descriptionPoste'=>'required|min:3'
]);
$data2 = $request->validate([
'nomEntreprise'=>'required|min:3',
'adresseEntreprise'=>'required|min:3'
]);
$newEnterprise = Entreprise::create($data2);
Poste::create($data + [
'idEntreprise' => $newEnterprise->id
]);
return back();
}