1

Yii CMS

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

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

从一组链接中,我一次提取一个链接,如果类别模式适合,我想存储 url;

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)
4

2 回答 2

3

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

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

编辑,

对不起,看错了你的问题!对于唯一键(非主键),您可以尝试以下扩展:

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

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

于 2012-09-16T16:07:37.947 回答
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;

}
于 2012-09-16T16:43:07.780 回答