If the register exists update, else, insert :)

Hi, I’m new to Yii framework (and I’m implementing it to all new projects with my team), and I have a question which I couldn’t find a solution for neither on forum or on documentation.

I have a table which rows needs to be updated if a field already exists (unique) or be inserted if there’s not.

I was able to make it that way:




$modelTest = ModelTest::model()->find('secondField=:secondField', array(':secondField' => $secondField));

if(!$modelTest) {

	$modelTest = ModelTest::model();

	$modelTest->isNewRecord = true;

}

$modelTest->loremIpsum = 'dolor sit amet';

$modelTest->save(false); // Saves ignoring the validation, just for test purposes



I think that redeclaration is oddly ugly, so, isn’t there an easier way?

Thanks in advance :)

i looked over at http://www.yiiframework.com/doc/api/CActiveRecord and couldn’t really find any method that does what asked.

in all honestly, it’s not that ugly… except for this line (which is not needed):


$modelTest->isNewRecord = true;

oh and,


$modelTest = ModelTest::model();

should be


$modelTest = new ModelTest();

since you are creating an instance of a class due to no previous record existing.

I’m preferring this common 2 line pattern:


if (($model=ModelTest::model()->find(...))===null)

  $model=new ModelTest;



Some might find this ugly, too (just dig the forum for discussion on coding style). But to me it’s a pattern i got used to very quickly.

where is the code for update part???