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

Upgrading Phalcon 2 to 3 - difference in model relations

Hi there,

we're updating a large application from Phalcon 2 to 3. We've found that model relations behave differently. I can't find anything in the changelog and was hoping someone could help explain.

It seems that in Phalcon 2, relations are refreshed on each access. In Phalcon 3 the related object is stored and not refreshed. Is this correct?

Here is an example of sorts with a unit test, I can post more code if helpful:

// say we have a robot with 2 parts
$this->assertEquals(2, count($robot->Parts));

// add a new part without referencing the relation
$part = new Part();
$part->name = 'Arm';
$part->robotId = $robot->Id;
$part->save();

// the robot now has 3 parts
$this->assertEquals(3, count($robot->Parts));

In Phalcon 2 this works - $robot->Parts is correctly updated when I check the 2nd time. In Phalcon 3 the behaviour is different. The first access to robot->Parts caches the object and it is n longer refreshed.

I can't find this in the documentation on upgrading. Thanks!

I think there were no such changes

Could you check the 'reusable' definition of relationships?

edited Oct '18

Thanks Degiovanni, a useful tip!

We have not set 'reusable' on any relation. I started investigating whether this property behaves differently on Phalcon 2 and 3, and it does.

On Phalcon 2, 'reusable' works as I would expect:

reusable == false -> the relation is queried every time

reusable == true -> the relation is only queried once

On Phalcon 3 however, when I use the relation alias notation, the relation is only queried once, even when 'reusable' = false is set. But when I use the 'getRelated' method, it behaves as I would expect and queries it every time.

// in the model - 'reusable' => false
$robot->Parts; // first query
$robot->Parts; // does not query the relation again

$robot->getRelated('Parts'); // queries it again
$robot->getRelated('Parts'); // queries it again

I think I might file a bug report but want to see first whether there is something I've missed and this is expected behaviour.

Bug filed: https://github.com/phalcon/cphalcon/issues/13531

Thanks for putting me on the right track Degiovanni.