简体   繁体   中英

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. while creatsing a new Atm, i also want to create new atm_devices that are related to the Atm. 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. when i add new Atm the id starts from 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). this is creating "Integrity constraint violation: 1062 Duplicate entry" because the numbers from 1 to 60 are already occupied for the 60 atm_devices. here is my code ` $atm1 = new Atm; $atm->name = $request->get('name'); $atm->ip_address = $request->get('ip_address'); $atm->save(); $atmDevice1 = new 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]);`

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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