0

我使用 Yii MVC 开发了一个脚本,但索引键和标准有问题。

我想防止插入已经存储在数据库中的记录;

我的示例,每次都无法检查并尝试添加新记录。

为什么 ?以及如何做到这一点?

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21-/popular/category/1.html' for key 'index_link'. The SQL statement executed was: INSERT INTO `categories` (`server_id`, `website_id`, `slave_category_id`, `link`, `name`, `image`, `videos`, `status`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7)

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `server_id` int(11) NOT NULL,
  `website_id` int(11) NOT NULL,
  `slave_category_id` int(11) NOT NULL,
  `link` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `videos` int(11) NOT NULL,
  `status` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_link` (`website_id`,`link`),
  UNIQUE KEY `index_name` (`website_id`,`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=332 ;

PK 是 id;另一个索引,是 website_id + link;另一个索引是 website_id + name;

以下代码无法检查并阻止插入:1

    $criteria_categories = new CDbCriteria();
                                    $criteria_categories->condition = " `server_id`=':server_id' and `website_id`=':website_id' and `link`=':link' and `name`=':name' ";
                                    $criteria_categories->params = array(
                                        ':server_id' => $model_website->server_id,
                                        ':website_id' => $model_website->id,
                                        ':link' => $matches_url[$value->link][$key2],
                                        ':name' => $matches_url[$value->name][$key2],
                                   );
$record_categories = Categories::model()->find($criteria_categories);
print_r($record_categories);
if (!$record_categories) {
$model_categories = new Categories();
$model_categories->server_id = $model_website->server_id;
$model_categories->website_id = $model_website->id;
$model_categories->slave_category_id = 1; //??
$model_categories->link = $matches_url[$value->link][$key2];
$model_categories->name = $matches_url[$value->name][$key2];
$model_categories->image = $matches_url[$value->image][$key2];
$model_categories->videos = 0;
$model_categories->status = 0;
$model_categories->save();
}
4

1 回答 1

3
$criteria_categories->condition = " `server_id`=':server_id' and `website_id`=':website_id' and `link`=':link' and `name`=':name' ";

你有几个错误正在发生。一是语法。如果使用参数绑定(这是一件好事),你不想引用参数。

也就是说,写:link而不是':link'.

上述条件也不能正确检查具有您的两个唯一键中的任何一个的现有记录。尝试以下操作:

$criteria_categories->addCondition("`server_id`=:server_id AND `website_id` = :website_id
AND (`link`=:link OR `name` = :name)");

这两个都正确引用,并且如果您的两个唯一键中的任何一个匹配,就会找到记录,而不是要求两者都匹配。

于 2013-01-20T19:18:40.247 回答