We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Update related records

Hi, I have the following relationship between models:

In the initialize method of 'Competencia' model I have

$this->hasMany('CompetenciaId', 'Competenciafuncion','CompetenciaId');

Then in 'Competenciafuncion' model initiliaze method:

$this->belongsTo('CompetenciaId', 'Competencia', 'CompetenciaId', array("foreignKey" => true));

In my program I need to update 'Competenciafuncion' records, some relations might be deleted while others might be added so I first delete related records and add the new relations like this:

$funciones = array();
$funcionesId = $this->request->getPost("funciones");
for($i=0;$i<count($funcionesId);$i++){
     $funciones[$i] = new Competenciafuncion();
    $funciones[$i]->FuncionId = $funcionesId[$i];
}
$competencia->competenciafuncion->delete();
$competencia->competenciafuncion = $funciones;
$competencia->save();

The delete part is working but the new relations aren't added, what am I doing wrong?



98.9k

Check if any messages are being generated:

if (!$competencia->save()) {
    foreach ($competencia->getMessages() as $message) {
        echo $message;
    }
}
edited Oct '14

No messages are generated, in fact changes in parent model are saved correctly. For example:

$competencia->CategoriaNombre = $this->request->getPost("CompetenciaNombre", "striptags");
$competencia->CompetenciaDefinicion = $this->request->getPost("CompetenciaDefinicion", "striptags");

Check if any messages are being generated:

if (!$competencia->save()) {
  foreach ($competencia->getMessages() as $message) {
      echo $message;
  }
}


33.8k

¿Has comprobado el log de errores de apache, a ver si dice algo? De igual forma, tiene pinta de que no se añaden porque no existen (o algo así). Y yo hago lo mismo para actualizar registros, excepto que uso update().

Did you check apache's error log, so maybe it will tell you something? Anyway, it looks like $funciones is empty (or something). I do the same for updating records, except that I use update().

¿Has comprobado el log de errores de apache, a ver si dice algo? De igual forma, tiene pinta de que no se añaden porque no existen (o algo así). Y yo hago lo mismo para actualizar registros, excepto que uso update().

Did you check apache's error log, so maybe it will tell you something? Anyway, it looks like $funciones is empty (or something). I do the same for updating records, except that I use update().

@RomperPC no hay nada relacionado en los logs de apache, los cambios en el modelo de Competencia sí se guardan pero no los relacionados ya he utilizado tanto update() como save() sin éxito. Si no aplico el método delete() sí se guardan las relaciones pero estas son duplicadas, por eso intento hacer un borrado antes de la inserción. Alguna otra sugerencia?

There's nothing in the apache logs, changes in 'Competencia' model are successfully saved however changes in related model are not. I have tried bothe update() and save() methods without any success. If delete() method is not used before inserting relations the save() method works but it adds all relations again even if they are duplicated.



33.8k

1) Tu forma de actualizar es correcta (yo lo hago igual, o tengo registros relacionados no deseados).

2) Prueba a cambiar array("foreignKey" => true) por array("foreignKey" => array("message" => "FK no valida.", "action" => Phalcon\Mvc\Model\Relation::ACTION_RESTRICT)).

3) Saca un var_dump() de los registros asociados a ver.


1) The form you update is right (I do the same, so I don't have not wanted relationships).

2) Try changing array("foreignKey" => true) to array("foreignKey" => array("message" => "FK not valid.", "action" => Phalcon\Mvc\Model\Relation::ACTION_RESTRICT)).

3) Do a var_dump() of the related records of the variable.

edited Oct '14

1) Tu forma de actualizar es correcta (yo lo hago igual, o tengo registros relacionados no deseados).

2) Prueba a cambiar array("foreignKey" => true) por array("foreignKey" => array("message" => "FK no valida.", "action" => Phalcon\Mvc\Model\Relation::ACTION_RESTRICT)).

3) Saca un var_dump() de los registros asociados a ver.


1) The form you update is right (I do the same, so I don't have not wanted relationships).

2) Try changing array("foreignKey" => true) to array("foreignKey" => array("message" => "FK not valid.", "action" => Phalcon\Mvc\Model\Relation::ACTION_RESTRICT)).

3) Do a var_dump() of the related records of the variable.

Gracias por tu ayuda @RompePC, pude resolver el problema de la siguiente manera:

Thanks @RompePC I was able to solve the problem in the following way:

As you can see in this stackoverflow question if you do some operations with related records, for some reason, you have to load the record again and then make some other changes. It might be a bug, I don't know but his worked:

$competencia->competenciafuncion->delete();
$competencia = Competencia::findFirst("CompetenciaId={$competenciaId}");
$competencia->competenciafuncion = $funciones;
$competencia->save();


33.8k

Pues yo no tengo ese problema, yo lo hago todo de tirón. Ahí pasa algo raro.

I don't have that problem, I do it all in a row. There's something strange there.

Pues yo no tengo ese problema, yo lo hago todo de tirón. Ahí pasa algo raro.

I don't have that problem, I do it all in a row. There's something strange there.

@RompePC which version of phalcon do you have?



33.8k
edited Oct '14

Pues yo no tengo ese problema, yo lo hago todo de tirón. Ahí pasa algo raro.

I don't have that problem, I do it all in a row. There's something strange there.

@RompePC which version of phalcon do you have?

1.3.3