2016-07-21 44 views
0

早上好,CakePHP 3:SQLSTATE [23000]數據庫錯誤

我正在開發一個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' 
     ]); 
    } 
+0

您只需要將user_id插入評論表中,評論者將註冊到 – pradeep

回答

0

按照你的數據庫結構和定義的約束

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

需要,因爲這個約束限制你的更新查詢先刪除此約束。

根據我的經驗,不需要使用UPDATE CASCADE。所以使用下面的約束。

ALTER TABLE `comentario` 
    ADD CONSTRAINT `comentario_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE; 
相關問題