使用Yii活动记录从DB读取多行

时间:2013-04-25 18:27:59

标签: php activerecord model yii

我希望能够使用Yii框架读取多行,而无需创建多个模型对象。考虑到这一点,我正在设置一个CDbCriteria,其条件为RowName =:param0或RowName = param1 ... RowName = ParamN和相应的参数值。

我的问题有两个问题。首先是findall失败了。第二个是我不知道如何从findall调用中获取错误代码(因此返回“heartBeat”行)。

class Xactions extends CActiveRecord
{
.
.
.
//example $requests data: '192.168.1.162, 192.168.1.161'
//This function should return a Xactions model which is associated with any rows
// where tcpAddress = $requests Comma separated values.
public static function HeartBeatmodel($requests)
{
        $criteria=new CDbCriteria;
        $request_arr =  explode(',', $requests);
        $criteria->condition=Xactions::request_condition("tcpAddress", count($request_arr));;
        $criteria->params= Xactions::request_params($request_arr);
        $return= Xactions::model()->findall($criteria);
        return "heartBeat"; // here for debugging purposes
}
public static function request_condition($column_name, $num_request){
        //want to end up with name=:param1 OR name=:param2....
        $return_str = "";
        for ($i = 0; $i < $num_request; $i++){
            $return_str .= $column_name . '=param' . (string)$i . ' ';
            if($i == $num_request -1 ) break; //prevents extra OR statement
            $return_str .= 'OR ';
        }
        return $return_str;
}

public static function request_params($requests){
        $return_arr = array();
        for ($i = 0; $i < count($requests); $i++){
            $return_arr['param' . (string)$i] = $requests[$i];
        }
        return $return_arr;
    }

1 个答案:

答案 0 :(得分:1)

也许这样的事情可以奏效?

class Xactions extends CActiveRecord {
        public static function HeartBeatmodel($requests) {
                $criteria = new CDbCriteria;
                $request_arr =  explode(',', $requests);

                for($request_arr as $request) {
                    $criteria->compare('tcpAddress', $request, false, 'OR');
                }

                return Xactions::model()->findAll($criteria);
        }

我正在使用CDbCriteria-&gt;比较,你可以在这里找到规范:http://www.yiiframework.com/doc/api/1.1/CDbCriteria#compare-detail

正如您所看到的,我将$partialMatch设置为false,将$operator设置为OR,以便它可以完成您想要的任务,对吧?

编辑:我刚刚意识到,最聪明的方法就是这样做

public static function HeartBeatmodel($requests) {
  $criteria = new CDbCriteria;
  $criteria->addInCondition('tcpAddress', explode(',', $requests));

  return Xactions::model()->findAll($criteria);
}