AR query with WHERE statement

Using Active Record, I’d like to insert a new row for numbers that do not exist, and if they do exist, I’d like to replace the values for that row.

I have a table with the following columns:

When using the code below, it will always perform an insert statement.

How can I perform a REPLACE INTO statement alternatively write a WHERE statement to achieve this?

Yii seems like a good framework, but seriously, I’ve posted 5 questions in the forum during the last few days and so far not even one single reply. Is there really a community who can help our or what? I’m starting to give up on this framework.

Hi yii_king, welcome to the forum.

I would do something like this:

$number = 1234;

$name = 'foobar';

// search for an existing record

$model = Model::model()->findByAttribute(array('number' => $number));

if ($model === null)


    // if not exists, create a new instance and save

    $model = new Model();

    // set attributes

    $model->number = $number;

    $model->name = $name;

    // save (insert)





    // if exists, update the existing one

    // update attributes

    $model->name = $name;

    // save (update)



I assume ‘id(pk)’ is an auto-increment in the above, and it’s just a rough sketch to illustrate the AR usage.

I strongly recommend you to read through the “Working with Database” sections of the guide, especially the “Active Record” section. :)

Ah, you have to be patient. :)

I’ve looked at your posts, and I think web service is rather an advanced topic where not so many people have good experience. You might be among the few who know well about web service, and is able to help others in this community. :rolleyes:

Hi there more than one way to do it

there is exists method on CActiveRecord that you can use to check it if a specific record exists if does you can update or else you add new one here is example in pseudo code

$result = ModelName::model()->exists( array conditons ) // conditions like you do in find or find All

// you can check if it returns true

if($result) {


} else {



Great, I’ve solved it now. Many thanks for your help and for pointing me towards that part of the guide :)