Yii查询复合唯一键的错误

时间:2012-09-16 15:53:04

标签: php sql yii

Yii CMS

我在表'category'中有一个唯一的复合键,website_id + link,Yii不支持这个键,所以我编写了自己的方法

一个网站有很多链接,每个链接都是独一无二的; 2个或更多网站可能具有相同的链接;因为链接可能不是绝对的;

从一系列链接中,我一次提取一个链接,如果类别模式适合,我想存储网址;

preg_match('/\/popular\/(.*?)\/1\.html/ims', $matches_website_url[1], $matches_url);

if(count($matches_url) > 0 &&
    $this->avoid_duplicate_category($website['id'], $matches_url[1]) )
{
    $category = new Category();
    $category->website_id = $website['id'];
    $category->link = $matches_url[0];
    $category->name = $matches_url[1];
    $category->urls = 0;
    $category->update = time();
    $category->save();
}

和方法

private function avoid_duplicate_category($website_id,$link)
{
    $query_category = Yii::app()->db->createCommand("select * from `category` where `website_id`='.$website_id.' and `link`='.$link.';");

    $results = $query_category->queryAll();

    if(count($results)>0)return false;
    else return true;

}

并返回错误:

CDbException

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Cute' for key 'name'. The SQL statement executed was: INSERT INTO `category` (`website_id`, `link`, `name`, `urls`, `update`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4)

2 个答案:

答案 0 :(得分:3)

我相信您应该能够通过在模型中添加以下内容来允许Yii处理复合键:

public function primaryKey()
{
    return array('website_id','link');
}

EDIT,

抱歉,误读了你的问题!对于唯一键(非主键),您可以尝试以下扩展名:

http://www.yiiframework.com/extension/composite-unique-key-validatable/

http://www.yiiframework.com/extension/unique-index-validator

答案 1 :(得分:0)

这就是答案:

private function avoid_duplicate_category($website_id,$link)
{
    $query = "select * from `category` where `website_id`=:website_id and `link`=:link;";

    $query_category = Yii::app()->db->createCommand($query);

    $query_category->bindParam( ':website_id', $website_id);

    $query_category->bindParam( ':link', $link);

    $results = $query_category->queryAll();

    if(count($results)>0)return false;
    else return true;

}