Phalcon - ORM Updating with save cause duplicate entries

1k Views Asked by At

I'm fighting with a problem for a considerable time, and I can't find a nice way to fix my issue.

Let's say I have two tables:

uses (id, name)

uses_phone (id, user_id, phone)

Supposing I have created a users (1, 'Mary') and her phones users_phones (1, 1, '123') (2, 1, '333')

If I want to update Mary, to change her name to "Maria":

The save() method will NOT delete the actual records in users_phone, but will insert new entries, and then I will have:

1, 1, 123 2, 1, 333 3, 1, 123 4, 1, 333

Which is the best way to solve this issue? I'm a bit confused. I like using Model instead PHQL (I like it too, but Models with ORM seems quie magic).

EDIT: Add code

I have updated my post to include the model relationships and a simplified version of my controller

Model Relationships:

class Users {
  ...
  $this->hasMany('xid', 'UsersTelephones', 'xid_user', ['alias' => 'UsersTelephones']);
  ...
}

class UsersTelephones { 
   ...
   $this->belongsTo('xid_user', '\Users', 'xid', ['alias' => 'Users']);
   ...
}

(very simplified) Controller code:

function update($xid) {
   ...
   $user = Users::findFirstByXid($xid);
   // $user->email = "..";

   $user_tfs = array();
   for ($i=0;$i<count($tfs_array);$i++)
   {
      $user_tfs[$i] = new UsersTelephones();
      $user_tfs[$i]->tf_number = $tfs_array[$i];
   }
   $user->UsersTelephones = $user_tfs;

   // ...

   $user->save()
}

Thanks for reading and please forgive my bad English.

1

There are 1 best solutions below

4
YOMorales On

Looking at your controller code, I have a few suggestions:

1) First, from where $tfs_array comes from?

2) You might also want to add the existing telephone record's id to the $user_tfs[$i] object, like: $user_tfs[$i]->id = $tfs_array[ID_OF_RECORD]; (you will need to add the record id to $tfs_array). This way, the ORM can interpret that the record already exists because the object has an id primary key.

3) Why do you want to iteratively add the UsersTelephones objects if all you want is to save the new name? You can go like:

$user = Users::findFirstByXid($xid);
$user->name = 'New Name';
$user->save();

4) You can also call the $model->update() method instead of save().

Here are more links: https://docs.phalconphp.com/en/3.2/db-models#create-update-records https://docs.phalconphp.com/en/3.2/db-models#create-update-with-confidence https://docs.phalconphp.com/en/3.2/db-models-relationships#updating-related-records