user2510555
user2510555

Reputation: 987

update if not inserted in yii

I want to update values in my table, if the values are not previously inserted. Here is my code-

function save_data($date, $game, $score) {
    $criteria = new CDbCriteria;
    $criteria->addCondition("date = '{$date}'");
    $data = array("date" => $date,
        "game" => $game,
        "score" => $score);
    $game_report = new GameReport();
    $game_report->attributes = $data;
    $game_report->save();
}

But it keeps on inserting duplicate values even though I have provided the date condition. Why? How do I update and not insert duplicate values?

Upvotes: 1

Views: 195

Answers (2)

Twisted1919
Twisted1919

Reputation: 2499

In order to make an update, you need to do it on an already loaded database model. In your case, this can be done as:

function save_data($date, $game, $score) {
    $criteria = new CDbCriteria;
    $criteria->addCondition("date = '{$date}'");

    $data = array(
        "date" => $date,
        "game" => $game,
        "score" => $score
    );

    $game_report = GameReport::model()->findByAttributes($data);
    if (empty($game_report)) {
        $game_report = new GameReport();
    }
    $game_report->attributes = $data;
    $game_report->save();
}

Also, to avoid sql injection, you should bind your condition params like:

$criteria->addCondition("date = :d");
$criteria->params[':d'] = $date;

or simply:

$criteria->compare('date', $date);

Upvotes: 4

Jelle de Fries
Jelle de Fries

Reputation: 875

This is how I generally do this:

$myModel = myModel::model()->findByAttributes(array('atr1'=>$atr1, 'atr2'=>$atr2));
if($myModel == null){
//create and save new reccord
}

I am not sure if this is the best way to do it or if Yii has a better way of doing it but it works.

Upvotes: 2

Related Questions