php - 使用一个表单将数据插入到两个表中。Laravel:错误完整性约束违规
问题描述
所以我想知道如何将数据插入到两个不同的表中,但是链接表 Poste(offer, ad) 和公司,每个广告都链接到一个公司,我创建了两个模型,只有一个控制器,邮政和公司以及 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,我已经被困住了,所以真的需要帮助!对不起我的英语我是法国人。
解决方案
如果您没有企业记录,则无法插入帖子记录。
在您的情况下,您在企业之前插入帖子,这就是错误。
您的商店功能将变为:
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();
}
推荐阅读
- rabbitmq - RabbitMQ 独占队列与独占消费者有什么区别?
- php - 如何从仍在 PHP 中运行的进程中获取部分输出?
- google-chrome - Service Worker 是否应该根据 W3C 规范更新推送或同步?
- excel - 如何在vba中的电子邮件主题行中找到两个单词?
- html - 如何忽略 XPATH 中的元素
- python - 让 PyCharm 在项目中使用 requirements.txt 文件中更新的 python 包的最可靠方法是什么?
- django - 如何允许 auth 用户从 django admin 发送时事通讯
- kubernetes - 在 Kubernetes 中为 Master 配置 AWS publicIP
- c++ - 如何从向量迭代的变换构造元组
- javascript - Javascript FileReader 如何访问 reader.onload?