cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Calling update on a model to change a belongsTo relation fails silently

Open nsossonko opened this issue 11 years ago • 3 comments

Code:

class Parent extends \Phalcon\Mvc\Model {
  public $id;
}

class Child extends \Phalcon\Mvc\Model {
  public $id;
  public $parentId;

  public function initialize() {
    $this->belongsTo('parentId', 'Parent', 'id', array('alias' => 'parent'));
  }

  public function hack() {
    unset($this->parent);
    unset($this->_related['parent']);
  }
}

/**
 * Assume we have two parents and two children with IDs 1 & 2 for both.
 * Child 1 belongs to Parent 1, etc.
 */
$child = Child::findFirst(1);
$parent = $child->parent;
$child->parentId = 2;
$child->update(); // This returns true but does not update the parentId

/**
 * Hacky way to make it work
 */
$child = Child::findFirst(1);
$parent = $child->parent;
$child->hack();
$child->parentId = 2;
$child->update(); // Now it will update correctly

nsossonko avatar Nov 09 '15 20:11 nsossonko

Did anyone fixed or resolved it? I also got this problem

Zaszczyk avatar Sep 27 '16 09:09 Zaszczyk

Less hacky way - add method to Child:

public function getParent()
{
    return $this->getRelated('parent')
}

and

$parent = $child->getParent();

This should work i think. Also IDE friendly because you can just add phpdoc on getParent method. Without setting reusable getParent() method will make a query each time. So set returned value from getRelated to property or use reusable. The problem is this _related array.

Jurigag avatar Sep 27 '16 09:09 Jurigag

Thank you for contributing to this issue. As it has been 90 days since the last activity, we are automatically closing the issue. This is often because the request was already solved in some way and it just wasn't updated or it's no longer applicable. If that's not the case, please feel free to either reopen this issue or open a new one. We will be more than happy to look at it again! You can read more here: https://blog.phalconphp.com/post/github-closing-old-issues

stale[bot] avatar Apr 16 '18 23:04 stale[bot]