Yii1:将每条记录保存到数据库中

Yii1: Save each records into database

目前,我无法保存由SQL生成的每条记录。由于我只能保存生成列表的最后一条记录。

这是我的代码。

$db = Yii::app ()->db;
$sql = 'SELECT  "product", "type", "retailerId", SUM("total") AS "total" 
                                                        FROM "Sales" 
                                                        GROUP BY K."product", C."type", K."retailerId" ';

$rs = $db->createCommand ( $sql )->query ();
while ( $_o1 = $rs->read () ) {

    $_col_no = null;

    switch ( $_o1['product'] ) {
        case 1:
            $_col_no = 'D';
            break;

        case 3:
            $_col_no = 'G';
            break;

        default:
            switch ( $_o1['type'] ) {
                case 'A':
                    $_col_no = 'F';
                    break;

                case '2':
                    $_col_no = 'E';
                    break;

                case '3':
                    $_col_no = 'H';
                    break;
            }
            break;
    }

    if ( !$_col_no ) {
        continue;
    }
    $data[$_col_no]['agent'][$_o1['retailerId']] = $_o1['total'];
    $data[$_col_no]['total'] += $_o1['total'];
}
foreach ( $data as $_col1 => $_info1 ) {
    foreach ( $_info1['agent'] as $_index => $_value ) {
        if ( !$o = self::model ()->findByAttributes ( array(
            'Code' => $code ,
            'retailerId' => $o_retailerId ,
                ) ) ) {

            $o = new self();

            $o->id = Utils::getUniqId ();
            $o->retailerId = $_index;  //have to save every retailerId
            $o->Code = 0;
            ///$o->total = have to save total relavant to each retailer                     
        }
    }
}

if ( !$o->save () ) {
    $_errors = current ( $o->getErrors () );
    throw new Exception ( $_errors[0] );
}

所以这里当我打印 $list 时,它会得到所有的 retailerId。但我不知道如何将每条记录保存在唯一 $o->id 下。提前致谢。

显然,它只会保存最后一条记录,因为您在 foreach 循环之外调用保存。您需要将其移入内部,以便每次迭代都调用 save()

所以移动这部分代码

if ( !$o->save () ) {
    $_errors = current ( $o->getErrors () );
    throw new Exception ( $_errors[0] );
}

在嵌套的里面 foreach

foreach ( $data as $_col1 => $_info1 ) {
    foreach ( $_info1['agent'] as $_index => $_value ) {
        if ( !$o = self::model ()->findByAttributes ( array(
            'Code' => $code ,
            'retailerId' => $o_retailerId ,
                ) ) ) {

            $o = new self();

            $o->id = Utils::getUniqId ();
            $o->retailerId = $_index;  //have to save every retailerId
            $o->Code = 0;
            ///$o->total = have to save total relavant to each retailer 

           //call save here to save the current record  
           if ( !$o->save () ) {
              $_errors = current ( $o->getErrors () );
              throw new Exception ( $_errors[0] );
           }                  
        }
    }
}