I have 2 models, which are tree and branch.
The relationship between these model is 1 optional tree to many optional branch.
There is no issue to have 1 tree with 0 or many branch, but encounter issue when to have 1 branch with 0 tree.
Output: Message: The Tree does not exist. Field: tree_id Type: ConstraintViolation
<?php
//CREATE TABLE tree
//( tree_id VARCHAR NOT NULL DEFAULT md5(now()::TEXT||random()) PRIMARY KEY,
// name VARCHAR NOT NULL
//);
class Tree extends Phalcon\Mvc\Model {
public $tree_id; //VARCHAR NOT NULL DEFAULT md5(now()::TEXT||random()) PRIMARY KEY,
public $name; //name NOT NULL,
public function initialize() {
$this->setSource('tree');
$this->hasMany('tree_id', 'Branch', 'tree_id', array(
'foreignKey' => array('message' => 'The Tree cannot be deleted because it is being used by Branch.')
));
}
}
<?php
//CREATE TABLE branch
//( branch_id VARCHAR NOT NULL DEFAULT md5(now()::TEXT||random()) PRIMARY KEY,
// tree_id VARCHAR DEFAULT NULL REFERENCES tree (tree_id),
// name VARCHAR NOT NULL
//);
class Branch extends Phalcon\Mvc\Model {
public $branch_id; //VARCHAR NOT NULL DEFAULT md5(now()::TEXT||random()) PRIMARY KEY,
public $tree_id; //VARCHAR DEFAULT NULL REFERENCES tree (tree_id),
public $name; //VARCHAR NOT NULL
public function initialize() {
$this->setSource('branch');
$this->belongsTo('tree_id', 'Tree', 'tree_id', array(
'foreignKey' => array('message' => 'The Tree does not exist.')
));
}
}
<?php
class TestController extends Phalcon\Mvc\Controller {
public function createAction() {
\Phalcon\Mvc\Model::setup(array(
'notNullValidations' => false
));
$branch = new Branch();
$branch->branch_id = 'branch1';
$branch->name = 'branch 1';
$branch->tree = null;
$branch->tree_id = null;
if (!$branch->save())
foreach ($branch->getMessages() as $message) {
echo "Message: ", $message->getMessage() . '<br/>';
echo "Field: ", $message->getField() . '<br/>';
echo "Type: ", $message->getType() . '<br/>';
}
}
}