如何在Yii MVC中管理多个组合索引键?

时间:2013-01-20 18:18:36

标签: php frameworks yii

我使用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();
}

1 个答案:

答案 0 :(得分: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)");

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