问题
I'm getting the following error when trying to insert a record into the table:
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (invoice.quotes, CONSTRAINT quotes_ibfk_1 FOREIGN KEY (contacts_id) REFERENCES Contacts (id))
I have a relationship setup between two tables 'contacts' and 'quotes'. 'quotes' has a foreign key set up contacts_id.
The Add method in my quotes controller looks like this:
public function add() {
$this->log('Quote Controller --> Add Method...1');
$this->log($this->request->data);
if ($this->request->is('post')) {
$this->Quote->create(); // This line writes the details to the database.
if ($this->Quote->save($this->request->data)) {
$this->Session->setFlash('Your quote has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your quote.');
}
}
}
Any help appreciated.
回答1:
The error happens when you don't have the correct foreign key when trying to save the data.
I am guessing the "contacts_id" value inside $this->request->data is null / empty. You might want to add debug($this->request->data); after $this->Quote->create();
And also it seems that you don't follow the convention of CakePHP. Your contacts_id field should be contact_id. That might help to fix the problem.
来源:https://stackoverflow.com/questions/16640084/cakephp-cant-insert-record-with-foreign-key-error