CakePHP 3:SQLSTATE [23000]数据库错误

时间:2016-07-21 04:32:56

标签: cakephp

早上好,

我正在开发一个CakePHP 3应用程序,其中登录的用户可以发表评论。登录后,我尝试发布一些评论,我收到以下数据库错误:SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( aenterprises . comentario , CONSTRAINT comentario_ibfk_1 FOREIGN KEY ( user_id ) REFERENCES个用户( ID为) ON DELETE CASCADE ON UPDATE CASCADE)

我该如何解决这个问题?

用户表

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `nome` varchar(200) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

comentario表

CREATE TABLE `comentario` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `autor` varchar(200) NOT NULL,
  `comentario` mediumtext NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `comentario`
--
ALTER TABLE `comentario`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`) USING BTREE;

--
-- AUTO_INCREMENT for dumped tables
--
ALTER TABLE `comentario`
  ADD CONSTRAINT `comentario_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

UsersTable.php - 初始化函数:

 public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('Comentario', [
            'foreignKey' => 'user_id'
        ]);
    }

ComentarioTable.php - 初始化功能

 public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('comentario');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);
    }

1 个答案:

答案 0 :(得分:0)

根据您的数据库结构和定义的约束

.git

您需要首先删除此约束,因为此约束限制您更新查询。

根据我的经验,不需要使用UPDATE CASCADE。所以使用下面的约束。

ALTER TABLE `comentario`
  ADD CONSTRAINT `comentario_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;