使用InnoDb與foreignkey
在數據庫中設置。在Phalcon也設置虛擬鍵。在刪除記錄時得到低於錯誤從phalcon由於Foreign Key
設置和還有子表中的數據。Phalcon:顯示花哨錯誤消息而不是標準異常
My Objective is to display fancy error message to user when this error displayed.
顯示錯誤:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`invoice`.`invoice`, CONSTRAINT `Invoice.CustomerId` FOREIGN KEY (`CustomerId`) REFERENCES `customer` (`Id`))
#0 [internal function]: PDOStatement->execute()
#1 [internal function]: Phalcon\Db\Adapter\Pdo->executePrepared(Object(PDOStatement), Array, Array)
#2 [internal function]: Phalcon\Db\Adapter\Pdo->execute('DELETE FROM `in...', Array, Array)
#3 [internal function]: Phalcon\Db\Adapter->delete(Array, '`Id` = ?', Array, Array)
#4 C:\wamp\www\invoice\app\controllers\CustomerController.php(140): Phalcon\Mvc\Model->delete()
#5 [internal function]: CustomerController->deleteAction('3')
#6 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(CustomerController), 'deleteAction', Array)
#7 [internal function]: Phalcon\Dispatcher->_dispatch()
#8 [internal function]: Phalcon\Dispatcher->dispatch()
#9 C:\wamp\www\invoice\public\index.php(42): Phalcon\Mvc\Application->handle()
#10 {main}
花式錯誤消息,我想顯示用戶:
The customer cannot be deleted because other invoices are using it
這是我的模型看起來像:
<?php
class Customer extends \Phalcon\Mvc\Model
{
public $id;
public $name;
public $street;
public $city;
public $country;
public $postalCode;
public $phone;
public $mobile;
public $fax;
public $email;
public $web;
public function initialize()
{
$this->setSchema("invoice");
$this->setSource("customer");
$this->hasMany(
'Id',
'Invoice',
'Id',
[
'alias' => 'Invoice',
'foreignKey' => [
'message' => 'The customer cannot be deleted because other invoices are using it',
]
]
);
}
public static function find($parameters = null)
{
return parent::find($parameters);
}
public static function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
public function getSource()
{
return 'customer';
}
}
?>
完整代碼可在github以備參考。
僅供參考:模型和控制器是使用'php-devtools'創建的,我相信'關係中不會有任何問題' –
抓住異常,然後處理它以適合您。 http://php.net/manual/en/language.exceptions.php – yogur