所以我想知道如何將數據插入到兩個不同的表中,但 linke,表 Poste(offer,ad)和公司,每個廣告都鏈接到一個公司,我創建了兩個模型,只有 1 個控制器,Post 和 Company 以及 Postecontroller。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,CONSTRAINT postes_identreprise_foreign FOREIGN KEY (idEntreprise) REFERENCES entreprises (id) ON DELETE CASCADE) .我是新來的,剛開始學習 laravel,我已經卡住了,所以請真的需要幫助!對不起我的英語我是法國人。
1 回答

有只小跳蛙
TA貢獻1824條經驗 獲得超8個贊
如果您沒有企業記錄,則不能插入帖子記錄。
在您的情況下,您在企業之前插入帖子,這就是錯誤。
您的商店功能將變為:
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();
}
- 1 回答
- 0 關注
- 186 瀏覽
添加回答
舉報
0/150
提交
取消