Model Issue

hi

I have two models, sale and stock. When I save new sale entry then I add entry in stock table in database as well. When I update sale entry (actionUpdate) then in stock table it inserts new entry, but I want to update current record in stock table (not inserting new entry).Following is my update sale code:

SALE MODEL

public function actionUpdate($id)

{

$model=$this->loadModel($id);

if(isset($_POST[‘Sale’]))

{

$model->attributes=$_POST[‘Sale’];

if($model->save(false)) {

$aData = array(“sale_id”=>$model->id, “product_id”=> $_POST[‘Sale’][‘productid’]

,“sale_price”=>$_POST[‘Sale’][‘sale_price’], “sale_quantity”=> $_POST[‘Sale’][‘sale_quantity’]);

$this->actionSaveStock($aData);

$this->redirect(array(‘view’,‘id’=>$model->id));

}

$this->render(‘update’,array(

‘model’=>$model,

));

}

public function actionSaveStock($aData) {

$stock = new Stock();

$stock->module_id = Constants::STOCK_SALE;

$stock->master_id = $aData["sale_id"];

$stock->product_id = $aData["product_id"];

$stock->description = "Sale Product";

$stock->sale_price = $aData["sale_price"];

$saleQty = 0;

$saleQty = $aData["sale_quantity"];

$stock->stock_out = $saleQty;

if($stock->save(false)) return true;

else return false;

}

You need to change this


$stock = new Stock();

to something like this




if (... some condition...) {

    $stock = Stock::model()->find('master_id = :id', array(':id' => $aData["sale_id"]));

} else {

    $stock = new Stock();

}



"Some condition" here is how you determine whether it is insert or update (for example, you can pass extra param to your function)

Actually this can be done in model’s afterSave() hook. See isNewRecord also.

Thanks ORey it solved my problem