public function afterSave() {
$command = Yii::app()->db->createCommand('SELECT SUM(subtotal) FROM pembelian_detail WHERE pembelian_detail.id_pembelian=:id_pembelian');
$command->bindValue(':id_pembelian', $this->id_pembelian);
$update=Pembelian::model()->update(array($this->total => $command->queryScalar));
$update->save();
}
I’m not sure if the queryScalar placement is correct, because this code makes this error :
I want to count the total from subtotals. but this total column and subtotal column are in different table in db. I never use this kind of createCommand or queryScalar code before, so that’s why it’s a little bit confusing for me.
well, yes there is an update method. this $command->queryScalar supposed to contains the value of
$command = Yii::app()->db->createCommand('SELECT SUM(subtotal) FROM pembelian_detail WHERE pembelian_detail.id_pembelian=:id_pembelian');
$command->bindValue(':id_pembelian', $this->id_pembelian);
but I think my code is wrong, so that’s why the error appears. and I’m not sure if $update=Pembelian::model()->update(array(‘total’ => $command->queryScalar)); is a right code. but I’ll give it a try. thanks
public function afterSave() {
//save total
$command = Yii::app()->db->createCommand('SELECT SUM(subtotal) FROM pembelian_detail WHERE pembelian_detail.id_pembelian=:id_pembelian');
$command->bindValue(':id_pembelian', $this->id_pembelian);
Pembelian::model()->updateByPk($this->id_pembelian, array($this->total => $command->queryScalar()));
}
but, I got this error : No columns are being updated for table “pembelian”.
this is my newest code to update total column from the sum of subtotals:
public function afterSave() {
//save total
$command = Yii::app()->db->createCommand('SELECT SUM(subtotal) FROM pembelian_detail WHERE pembelian_detail.id_pembelian=:id_pembelian');
$command->bindValue(':id_pembelian', $this->id_pembelian);
Pembelian::model()->updateByPk($this->id_pembelian, array('total'=>$command->queryScalar()));
}