CDbCommand无法执行SQL语句:SQLSTATE [42S22]:找不到列YII

时间:2015-10-26 04:27:48

标签: yii

下面的评论关系:

return array(
        'product' => array(self::BELONGS_TO, 'Product', 'product_id'),
        'profile' => array(self::BELONGS_TO, 'Profile', 'profile_id'),
        'rating' => array(self::BELONGS_TO, 'Rating', 'rating_id'),
        'reviewcomments' => array(self::HAS_MANY, 'Reviewcomment', 'review_id'),
        'reviewhelpfuls' => array(self::HAS_MANY, 'Reviewhelpful', 'review_id'),
                    'commentCounts' => array(self::STAT, 'Reviewcomment', 'review_id'),
    );

以下控制器代码:

$criteria = new CDbCriteria();
           $criteria->addCondition("t.seoUrl = :seoUrl");
           $criteria->addCondition("t.published = 1");
           $criteria->params = array("seoUrl"=>$seoUrl);               
           $data['product'] = Product::model()->find($criteria);
           if($data['product']){
                $data['product']->hits = $data['product']->hits+1;
                $data['product']->save();
           } else{
               throw new CHttpException(404, "Invalid Request for product");
           }
           $product_id = $data['product']->id;
           $criteria = new CDbCriteria();
           $criteria->addCondition("t.product_id = '$product_id'");

           if(isset($_GET['rating']))
           {
               $rating_id = $_GET['rating'];
               $criteria->addCondition("t.rating_id = '$rating_id'");
           }           


           $criteria->addCondition('t.status = "approved"');

           if(isset($_GET['sort']))
           {
               $sorting = $_GET['sort'];
               if($sorting=='newest')
                   $criteria->order = "t.postDate DESC";
               elseif($sorting=='oldest')
                   $criteria->order = "t.postDate ASC";
               elseif($sorting=='rating_high')
                   $criteria->order = "t.rating_id DESC";
               elseif($sorting=='rating_low')
                   $criteria->order = "t.rating_id ASC";
           }

           $data['reviews'] = new CActiveDataProvider('Review', array(
                'criteria'=>$criteria,
                'pagination'=>array('pagesize'=>4)

            ));

现在,当我运行此代码时,我发现CDbCommand无法执行SQL语句:SQLSTATE [42S22]:找不到列:1054'where子句'中的未知列't.rating_id'

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

使用't'作为表的别名,开始使用getTableAlias(false, false) 在你的情况下,它将是:

$criteria->addCondition(Review::model()->getTableAlias(false, false).".rating_id = '$rating_id'");

更重要的是,这段代码尖叫SQL注入

$rating_id = $_GET['rating'];
$criteria->addCondition("t.rating_id = '$rating_id'");

切勿在未经处理的情况下使用用户输入。 Yii允许你绑定将为你转义的值 - 没有SQL注入的威胁(至少据我所知)。您应该像这样创建标准:

$criteria->addCondition(Review::model()->getTableAlias(false, false).".rating_id = :rating_id");
$criteria->params = array(
    ':rating_id' => $rating_id,
);