[Question] Is there a 'find or create' method?

Hi there,

I’m working on a data importation project, and I’d like to know if there is a ‘find or create’ method implemented on CActiveRecord. I had a look through the docs and did not find one. This is what I imagine it would do:




public function findOrCreate(CDbCriteria $criteria)

{

    if (!$model = self::model()->find($criteria)) {

        $model = self::model();

        // ... somehow assign the passed criteria ...

        $model->save();

    }

    return($model);

}



If such a method does not exist, how can I get some NVPs back from DbCriteria so that I can create the record?

Also, how can I can add syntax highlighting on PHP code when posting code snippets to this forum?

Many thanks,

Anthony

There is CActiveRecord.exists() method. "find or create" looks strange to me, because I never needed this. But you can easily implement it.

Thanks for the reply. CActiveRecord::exists() just looks the same as CActiveRecord::find() to me, only it returns a boolean instead of the record itself - possibly good for keeping down memory? What I’m doing is working on a data import proceedure, so I’m having to check to see if a database entry exists (if not, create) and then return. I need to do this a lot, and I’d rather just implement a ‘find or create’ method than have masses of if statements everywhere.

The only way I can see is to look at CDbCriteria::conditions and CDbCriteria::params, replace the place holders in CDbCriteria::conditions with the values in CDbCriteria::params, and then examine the string and turn it in to an array of name/value pairs, which I can then loop through, setting each one on the model.

I don’t think this is a very good way of doing it. Does anyone else have any ideas before I go ahead and hack this together?

Cheers,

Anthony

i would do it with

$model->search()

gii will always create your model with that function, which will automatically build your cdbcriteria

so something like


class Example extends CActiveRecord

{

...

        public function search()

        {

                $criteria=new CDbCriteria;

                // $criteria->compare('id',$this->id);

                $criteria->compare('titel',$this->titel,true);

...

                return new CActiveDataProvider(get_class($this), array(

                        'criteria'=>$criteria,

                ));

        }

}


// and in the controller

$model = new Example('search');

$model->attributes = $_POST['example'];

if (!$model->search())$model->save();

i guess instead of the cactivedataprovider you can use any other object which has as argument a CDbCriteria