On 9 January 2014 10:48, Daniel Hofmann <[email protected]>wrote:
> For example. I am trying to insert 5 devices, all with a device type of A.
> When I run the below code, it tries to insert another record in device type
> for A, even though it already exists, and I get an Integrity constraint
> violation
>
>
>
> foreach ($device_info as $info) {
>
>
> $device = new entityDevice();
> $device_type = new entityDeviceType();
>
> $device_type->setDeviceTypeName($device_type_name);
> $this->_entity_manager->persist($device_type);
>
> $device->setDeviceHostName($info[1]);
> $device->setDeviceSerialNumber($info[5]);
> $timestamp = strtotime($info[4]);
> $device->setExpirationDateDevice(date("Y-m-d", $timestamp));
> $this->_entity_manager->persist($device);
>
> $device->setDeviceType($device_type);
>
> // write changes to database
> $this->_entity_manager->flush();
> }
>
>
>
> This code tries to insert the same value, and fails. How can I tell
> Doctrine to just use the existing primary key since the data for the device
> type already exists?
>
This code is wrong - you are creating the same device type multiple times.
Instead of doing it like that, you should:
- 1) search for existing device types first
- 2) if none found, search for device types that were persisted but not
yet flushed (you should keep them in an array)
- 3) if none of the above is valid, create a new device type, persist it
and stuff it into that array for further lookups
> I did try the following code:
>
> if ($record = $type->findOneBy(array('device_type_name' => $info[3]))) {
> $device_type = $record;
> }
>
>
This only works after all device types have been flushed first. See the
approach I've described above
Marco Pivetta
http://twitter.com/Ocramius
http://ocramius.github.com/
--
You received this message because you are subscribed to the Google Groups
"doctrine-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/doctrine-user.
For more options, visit https://groups.google.com/groups/opt_out.