using InnoDb with foreignkey
setup in database. In Phalcon also setup virtual keys. getting below error when deleting records from phalcon due to Foreign Key
setup and also there is still data in child tables.
My Objective is to display fancy error message to user when this error displayed.
Showing Error:
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}
Fancy Error Message I wanted to display for user:
The customer cannot be deleted because other invoices are using it
This is my model looks like:
<?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';
}
}
?>
Full code is available in github in case for reference.
You have wrong relations written.
belongsTo arguments:
hasMany/hasOne arguments:
So in your case it should be for class customer:
$this->hasMany(
'id',
'Invoice',
'customerId',
[
'alias' => 'Invoices', // it's has many relations so better Invoices alias
'foreignKey' => [
'message' => 'The customer cannot be deleted because other invoices are using it',
]
]
);
In Invoice class:
$this->belongsTo('customerId', '\Customer', 'id', ['alias' => 'Customer']);
Not sure if this alone will fix your issue though.