Updating model through loop messes up my foreign keys

I have models Order and OrderAddress. Order has a 1-m relationship with OrderAddress.

When I iterate over the relations like the below, After the first iteration, calling save on the model is also updating all foreign keys on that model to the values of the object from the first iteration of the loop.

Example, before the code below is run, I have 4 rows in the database with the 2 foreign keys correctly pointing to the correct records.

 $order_addresses = OrderAddress::find(array(
   "conditions" => "order_id = :order_id: and active = 'Y'",
   "bind" => array("order_id" => $order->getId())
 ));
 foreach ( $order_addresses as $order_address ) {
   $order_address->save();
 }

After the save method is called after the first iteration, the SQL changes from

UPDATE `order_address` SET `validation_messages` = ? WHERE `id` = ?

to

UPDATE `order_address` SET `order_id` = ?, `validation_messages` = ? WHERE `id` = ?

which sets the foreign keys on these records to the value of the first iteration of the loop. This doesn't happen in a single part of the application- if I comment out where I first see it happening, then wherever I loop over the records somewhere else later in the code, it does the same thing.

I have tried using PHQL as well and this hasn't helped as I am guessing the models just use PHQL under the hood. Before saving, if I check the value of the foreign key objects, they are correct- it's rigth when save is called that they change. This is a major issue and I currently have no workaround.



48.3k

Just a tip but if you use a triple tilde and then php after that on the first line then it will syntax highlight for PHP. You need to have a line between the previous content though.



10.4k
edited Feb '15

Which version of your phalcon? if the version is below 1.3.4, please upgrade. and if it is equal or greater than 1.3.4,

class OrderAddress extends Model {
    public function initialize(){
        $this->keepSnapshots(true);
        $this->useDynamicUpdate(true);
    }
}

may help.



688

Hi there. Am using 1.3.4. I am using DynamicUpdate however I am not using keepSnapshot as this isn't the behaviour that I am wanting. There is a bug somewhere in the way the model must be cached- I can't unfortunately replicate the issue in a more basic version of my code as it isn't happening with all my models for some reason.

On Thu, Feb 5, 2015 at 7:38 PM, hu2008yinxiang [email protected] wrote: