繁体   English   中英

Laravel 5.2插入相关模型违反完整性约束

[英]Laravel 5.2 Inserting Related Models has Integrity constraint violation

我有两个表atms和atm_devices,其中atms表具有许多atm_devices。 在创建新的Atm时,我还想创建与Atm相关的新atm_devices。 在添加任何atm之前,我有15个atm和60个atm_devices,其中atm的ID为1到15(含),而atm_devices的ID为1到60(含)。 当我添加新的Atm时,id从16开始; 到目前为止没有错。 当创建atm_devices时,问题就开始了,其中第一个新创建的atm_devices会自动分配一个ID,该ID等于新atm的ID(在本例中为16)。 这将创建“违反完整性约束:1062重复项”,因为60个atm_devices已占用1到60之间的数字。 这是我的代码`$ atm1 = new Atm; $ atm-> name = $ request-> get('name'); $ atm-> ip_address = $ request-> get('ip_address'); $ atm-> save(); $ atmDevice1 =新的AtmDevice; $ atmDevice1-> name ='Top Cassette'; $ atmDevice1-> oid ='.1.3.6.1';

$atmDevice2 = new AtmDevice;
$atmDevice2->name = 'Cash Dispenser Second Cassette';
$atmDevice2->oid = '.1.3.6.1.4';
$atm->atmDevices()->saveMany([$atmDevice1, $atmDevice2]);`

用于外键的名称和用于关系定义的名称应相同,如下所示:

public function atmDevices()
{
    return $this->hasMany('App\AtmDevice', 'atm_id');
} //relationship definition


$table->foreign('atm_id')->references('id')->on('atms')->onDelete('cascade');//migration table states atm_id is a foreign key

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM