简体   繁体   English

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

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

I have two tables atms and atm_devices where atms table has many atm_devices. 我有两个表atms和atm_devices,其中atms表具有许多atm_devices。 while creatsing a new Atm, i also want to create new atm_devices that are related to the Atm. 在创建新的Atm时,我还想创建与Atm相关的新atm_devices。 before adding any atm, i have 15 atms and 60 atm_devices where the id of the atms is 1 to 15 inclusive and the id of the atm_devices is from 1 to 60 inclusive. 在添加任何atm之前,我有15个atm和60个atm_devices,其中atm的ID为1到15(含),而atm_devices的ID为1到60(含)。 when i add new Atm the id starts from 16; 当我添加新的Atm时,id从16开始; nothing wrong so far. 到目前为止没有错。 the problem starts when the atm_devices are created where the first newly created atm_devices is automatically assigned an id which equals the id of the new atm (in this case 16). 当创建atm_devices时,问题就开始了,其中第一个新创建的atm_devices会自动分配一个ID,该ID等于新atm的ID(在本例中为16)。 this is creating "Integrity constraint violation: 1062 Duplicate entry" because the numbers from 1 to 60 are already occupied for the 60 atm_devices. 这将创建“违反完整性约束:1062重复项”,因为60个atm_devices已占用1到60之间的数字。 here is my code ` $atm1 = new Atm; 这是我的代码`$ atm1 = new Atm; $atm->name = $request->get('name'); $ atm-> name = $ request-> get('name'); $atm->ip_address = $request->get('ip_address'); $ atm-> ip_address = $ request-> get('ip_address'); $atm->save(); $ atm-> save(); $atmDevice1 = new AtmDevice; $ atmDevice1 =新的AtmDevice; $atmDevice1->name = 'Top Cassette'; $ atmDevice1-> name ='Top Cassette'; $atmDevice1->oid = '.1.3.6.1'; $ 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]);`

The name used for the foreign key and that used on the definition of the relationship should be the same like so: 用于外键的名称和用于关系定义的名称应相同,如下所示:

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