CakePHP Can't insert record with foreign key error

坚强是说给别人听的谎言 提交于 2019-12-12 02:57:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!