cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Accessing relation in model causes dirty state to change to transient

Open nsossonko opened this issue 11 years ago • 7 comments

Code:

  class Parent extends \Phalcon\Mvc\Model {
    public $id;
    public function initialize() {
      $this->hasMany('id', 'Child', 'parent', array(
        'foreignKey' => array('action' => Relation::ACTION_RESTRICT),
        'alias'  => 'relatedchilds'));
    }
  }
  class Child extends \Phalcon\Mvc\Model {
    public $parent;
    public $id;
    public function initialize() {
      $this->belongsTo('parent', 'Parent', 'id', array(
          'alias' => 'relatedparent',
          'foreignKey' => array('message' => 'Must have parent')
      ));
    }
  }

  $children = Child::find(); // get all child records
  foreach ($children as $child) {
    echo "Initial state: {$child ->getDirtyState()} <br />";
    $parent = $child ->relatedparent;
    echo "After accessing parent - state: {$child ->getDirtyState()} <br />";
  }

Is this by design? If so, why? This is causing us big headaches in our application, so any help would be appreciated.

nsossonko avatar Oct 21 '15 15:10 nsossonko

I'm not sure how can this work:

$child = Child::find(); // this returns a resultset
  echo "Initial state: {$child ->getDirtyState()} <br />";
  $parent = $child ->relatedparent; // you can't do this

andresgutierrez avatar Oct 29 '15 16:10 andresgutierrez

What's the problem, I'm grabbing the related parent of the child...?

On Thu, Oct 29, 2015 at 12:27 PM, Andy Gutierrez [email protected] wrote:

I'm not sure how can this work:

$child = Child::find(); // this returns a resultset echo "Initial state: {$child ->getDirtyState()}
"; $parent = $child ->relatedparent; // you can't do this

— Reply to this email directly or view it on GitHub https://github.com/phalcon/cphalcon/issues/11042#issuecomment-152235361.

nsossonko avatar Oct 29 '15 16:10 nsossonko

Child::find() returns a resultset you can't access the related parent on a resultset.

andresgutierrez avatar Oct 29 '15 16:10 andresgutierrez

Oh, I see what you're saying...it's a mistake in the code. Just assume there's a foreach loop there and this is done on one of the actual models...sorry it was pseudo-code

nsossonko avatar Oct 29 '15 16:10 nsossonko

Should be clearer now, I updated the code

nsossonko avatar Oct 29 '15 16:10 nsossonko

Btw, is there any reason the dirty state should change if the property is being set to an object? That itself also doesn't make sense to me...this record is in the database and is going to be updated, why should it be in TRANSIENT state? Setting any other property on the record doesn't change the dirty state...

nsossonko avatar Nov 02 '15 14:11 nsossonko

This is fixed by PR #11055

nsossonko avatar Feb 18 '16 18:02 nsossonko