Yii how to use model update even if the record is new

I have a system which is very important to be as close to realtime as possible. For this reason when i'm fetching data from external source i want to use $model->update instead of executing 2 queries :

$model->find()
if(new)
    $model->save
else
    $model->update

This is too time consuming...can i use $model->update and if the record is new it will simply create it?

I looked at the code for update, but i'm not sure how to override it.

public function update($attributes=null)
{
    if($this->getIsNewRecord())
        throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
    if($this->beforeSave())
    {
        Yii::trace(get_class($this).'.update()','system.db.ar.CActiveRecord');
        if($this->_pk===null)
            $this->_pk=$this->getPrimaryKey();
        $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
        $this->_pk=$this->getPrimaryKey();
        $this->afterSave();
        return true;
    }
    else
        return false;
}

Answers


$model->save

works the same way you want. if the model is new it will insert and if model exist it will update. http://www.yiiframework.com/doc/guide/1.1/en/database.ar#updating-record

As we can see, we use the same save() method to perform insertion and updating operations. If an AR instance is created using the new operator, calling save() would insert a new row into the database table; if the AR instance is the result of some find or findAll method call, calling save() would update the existing row in the table.


Need Your Help

How to quickly load 50+ controls? vb.net winform

vb.net winforms load-time

I have a large form with many controls on it(50+). The logic to show all of these isn't complex at all, just a few checks here and there depending on the user. I've tried implementing a

Header is not showing with RelativeLayout

android listview relativelayout

I am using a ListView to show a standings table but the header is not showing:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.