Yii2 Update the entry if it exists

197 views Asked by At

Item $title defined earlier. I want what if found $find_title, update it with all fields from $title. Otherwise, create a new object

  $find_title = Title::find()->where(["upc" => $title->upc])->one();
                    if ($find_title != null) {
                        $title->id = $find_title->id;
                        $title->save();
                    } else {
                        $title->save();
                    }

It worked in the laravel.

1

There are 1 answers

0
Gabriel Alejandro López López On
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
    $id = $title->id;
    $find_title->attributes = $title->attributes;
    $find_title->id = $id;
    $find_title->save();
} else {
    $title->save();
}

Here you assign all attributes of $title to $find_title, restore id, and then save;