亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數據插入到具有單個表單的兩個表中。Laravel:錯誤違反完整性約束

將數據插入到具有單個表單的兩個表中。Laravel:錯誤違反完整性約束

PHP
qq_笑_17 2023-04-15 20:49:20
所以我想知道如何將數據插入到兩個不同的表中,但 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();

}


查看完整回答
反對 回復 2023-04-15
  • 1 回答
  • 0 關注
  • 186 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號