No problem to delete on delete1 action, but encounter 'The Head cannot be deleted because it is being used by Line.' error on delete2 action(with transaction).
/*
CREATE TABLE head
( head_id VARCHAR NOT NULL PRIMARY KEY,
name VARCHAR
);
*/
use Phalcon\Mvc\Model,
Phalcon\Db\Column,
Phalcon\Mvc\Model\MetaData;
class Head extends Phalcon\Mvc\Model {
public function initialize() {
$this->setSource('head');
$this->hasMany('head_id', 'Line', 'head_id', array(
'foreignKey' => array('message' => 'The Head cannot be deleted because it is being used by Line.')
));
}
}
/*
CREATE TABLE line
( line_id VARCHAR NOT NULL PRIMARY KEY,
name VARCHAR,
head_id VARCHAR NOT NULL REFERENCES head (head_id)
);
*/
use Phalcon\Mvc\Model,
Phalcon\Db\Column,
Phalcon\Mvc\Model\MetaData;
class Line extends Phalcon\Mvc\Model {
public function initialize() {
$this->setSource('line');
$this->belongsTo('head_id', 'Head', 'head_id', array(
'foreignKey' => array('message' => 'The Head does not exist.')
));
}
}
class TestController extends Phalcon\Mvc\Controller {
public function indexAction() {
}
public function createAction() {
$head = new Head();
$head->head_id = 'h1';
$head->name = 'head 1';
$line = new Line();
$line->line_id = 'l1';
$line->name = 'line 1';
$head->line = $line;
if (!$head->save()) {
foreach ($head->getMessages() as $message) {
echo $message . '<br/>';
}
}
}
public function delete1Action() {
//$manager = new Phalcon\Mvc\Model\Transaction\Manager();
//$transaction = $manager->get();
$line = Line::findFirst(array(
'line_id = :line_id:',
'bind' => array('line_id' => 'l1')
));
//$line->setTransaction($transaction);
$head = $line->head;
//$head->setTransaction($transaction);
if (!$line->delete()) {
try {
//$transaction->rollback();
} catch (Exception $e) {
}
foreach ($line->getMessages() as $message)
echo $message . '<br/>';
return;
}
if (!$head->delete()) {
try {
//$transaction->rollback();
} catch (Exception $e) {
}
foreach ($head->getMessages() as $message)
echo $message . '<br/>';
return;
}
//$transaction->commit();
}
public function delete2Action() {
$manager = new Phalcon\Mvc\Model\Transaction\Manager();
$transaction = $manager->get();
$line = Line::findFirst(array(
'line_id = :line_id:',
'bind' => array('line_id' => 'l1')
));
$line->setTransaction($transaction);
$head = $line->head;
$head->setTransaction($transaction);
if (!$line->delete()) {
try {
//$transaction->rollback();
} catch (Exception $e) {
}
foreach ($line->getMessages() as $message)
echo $message . '<br/>';
return;
}
if (!$head->delete()) {
try {
$transaction->rollback();
} catch (Exception $e) {
}
foreach ($head->getMessages() as $message)
echo $message . '<br/>';
return;
}
$transaction->commit();
}
}