CakePHP无法插入带有外键错误的记录 [英] CakePHP Can't insert record with foreign key error

查看:138
本文介绍了CakePHP无法插入带有外键错误的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试向表中插入记录时出现以下错误:

I'm getting the following error when trying to insert a record into the table:

错误:SQLSTATE [23000]:完整性约束违例:1452无法添加或更新子行:外键约束失败(发票引号,CONSTRAINT quotes_ibfk_1 FOREIGN KEY( contacts_id )参考联系人 id ))

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))

我有两个表'contacts'和'quotes'之间的关系设置。 'quotes'有外键设置了contacts_id。

I have a relationship setup between two tables 'contacts' and 'quotes'. 'quotes' has a foreign key set up contacts_id.

我的引用控制器中的Add方法如下:

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.');
            }            
        }
    }

推荐答案

当尝试保存数据时没有正确的外键时,会发生错误。

The error happens when you don't have the correct foreign key when trying to save the data.

我猜测contacts_id值在$ this-> request-> data为null / empty。您可能需要添加debug($ this-> request-> data); after $ this-> Quote-> create();

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();

也似乎你不遵循CakePHP的约定。您的contacts_id字段应为contact_id。这可能有助于解决问题。

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.

这篇关于CakePHP无法插入带有外键错误的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆