【问题标题】:Yii query with error for composite unique keyYii 查询复合唯一键错误
【发布时间】:2012-09-16 15:53:04
【问题描述】:

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)

【问题讨论】:

    标签: php sql yii


    【解决方案1】:

    我相信您应该能够通过将以下内容添加到您的模型中来允许 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

    【讨论】:

    • 这不是Pk,是唯一的key;我认为我可以重命名方法,yii会接受;我希望;等我试试;
    • public function rules() { // 注意:您应该只为那些 // 将接收用户输入的属性定义规则。 return array( ... array('website_id, link', 'primaryKey'), ... ); } public function primaryKey() { return array('website_id', 'link'); }
    • 是的,抱歉误读了您的问题!我添加了一些可能对您有所帮助的扩展程序的链接
    • 好的,但是为什么我的方法不起作用?为什么即使数据是重复的,它也会返回 true ? yii 为我推荐了一些复杂的东西
    【解决方案2】:

    这就是答案:

    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;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 2017-02-03
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 2015-03-28
      • 1970-01-01
      相关资源
      最近更新 更多