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

Setting related model to null - 'echo' statement changes behavior..??

Hi,

I have a model which references another model in a 'belongsTo' relationship:

class Property extends \Phalcon\Mvc\Model
{ ....
    public function initialize()
    {...
        $this->belongsTo('park_id', 'Park', 'id', array('alias' => 'Park'));
    }
}

The park/park_id can be null. In the scenario where property->park_id is set, and I want to change it to null, the following code works:

$property = Property::findFirstByid($id);
$property->park_id = null;
$property->save();

$property->park is null

However, when I insert, for example, an echo statement, property->park retains the old value

$property = Property::findFirstByid($id);
echo $property->park->name;
$property->park_id = null;
$property->save();

$property->park has old value.

Can someone explain to me why this is? Is there a better way to unset a related model?

Thanks in advance!



43.9k

Hi,

I think that this is because what you want to achieve must violate the ORM's logic .


// you ave a related park 
echo $property->park->name;
// so its relation key can't be null
$property->park_id = null;

Is there a better way to unset a related model?

Good question.



526
edited Aug '15

I've done some further experimentation, and I've noticed that once you reference an attribute of the related model, it becomes impossible to update the related model.

Consider the following:

$property = Property::findFirstByid($id);
$property->park = Park::findFirstById($newParkId);
echo $property->park->name;
$property->save();

Works as expected (i.e. property->park references the newPark).

$property = Property::findFirstByid($id);
echo $property->park->name;
$property->park = Park::findFirstById($newParkId);
echo $property->park->name;
$property->save();

Does not work as expected (i.e. property->park references the original Park, even though the second echo statement returns the newPark->name).

When trying to debug this issue, I've found that the Park gets updated fine, even in the save method the newPark is set.

In Property.php model:

public function save($data = null, $whitelist = null)
    {
        echo $this->park->name;
        return parent::save($data, $whitelist);
    }

Returns the newPark->name. I'm getting the feeling that this might be related to https://stackoverflow.com/questions/18346569/phalconphp-framework-how-to-update-a-model-object-and-the-related-object. However, the 'workaround' isn't really anything other than 'make sure you don't reference a related model attribute before saving'.

Saving properties on the Property object is not affected, and no errors/messages are returned.

I think I'm missing something here, maybe I'm not using the magic setters correctly..?