5

I'm trying to find an item and update it if it exists, or to create a new one if it does not exist. However, for some reason it seems to be trying to create a new object instead of updating in the event that that already exists in the database.

    $object = ObjectItem::firstOrNew(array('object_item_id'=>$userEditedObject['object_item_id'], 'object_id'=>$object_id));

    $object->setFields($userEditedObject);

    if($object->save()){
        return TRUE;
    } else {
        return FALSE;
    }

That code appears to be producing the error

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '113' for key 'PRIMARY'

This is strange, because I have used this before and it worked okay -- it just seems to be in this particular case.

Marcel Gruber
  • 6,668
  • 6
  • 34
  • 60

1 Answers1

2

It means that array $userEditedObject contains duplicate value for the primary key, which is usually "id".

You get $object and try to edit its primary key so that other row exists with same primary key causing the failure.

See what field is primary key for you application and make sure you are not creating any duplicates.

Margus Pala
  • 8,433
  • 8
  • 42
  • 52
  • 1
    I agree that the id of $userEditedObject is a duplicate value, but that's because the item already exists, and if that's the case, the firstOrNew should simply get the first item based on `object_id` and `object_item_id`. But you are right about trying to edit the primary key. In my model, I had the primary key as a fillable field, which is in fact wrong because it is auto incrementing in the db. So even though the ID was not actually being changed to a new value, it still considered as being so. Once I made the property to be not fillable, the error went away. – Marcel Gruber Apr 28 '15 at 14:46