Issue
Currently, I could not be able to save each record which is generated by SQL. Since I am only able to save the last record of the generated list.
This is my code.
$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] );
}
So here When I print the $list
it is given all retailerIds. But I don't know how to save each records under unique $o->id
. Thanks in advance.
Solution
Obviously, it will save the last record only because you are calling save outside the foreach
loop. You need to move it inside so that save()
is called for every iteration.
So move this part of code
if ( !$o->save () ) {
$_errors = current ( $o->getErrors () );
throw new Exception ( $_errors[0] );
}
inside the nested 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] );
}
}
}
}
Answered By - Muhammad Omer Aslam
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.