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

时间:2018-03-20 12:40:18

标签: php yii yii1.x

目前,我无法保存由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时,会给出所有零售商ID。但我不知道如何在唯一$o->id下保存每条记录。提前谢谢。

1 个答案:

答案 0 :(得分:0)

显然,它只保存最后一条记录,因为你在foreach循环之外调用save。您需要将其移动到内部,以便每次迭代都调用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] );
           }                  
        }
    }
}