Created
March 17, 2019 18:26
-
-
Save cronfy/065d17e1a2a85df5f67556c784a0f47b to your computer and use it in GitHub Desktop.
yii2 save new record instead of existing in db (replace with new object)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Допустим, есть объект yii2 ActiveRecord, созданный как $model = new Model(). | |
А надо сохранить его в БД вместо существующей записи. | |
Казалось бы, $model->id = <существующий id> ; $model->save(), но нет. | |
Надо сделать подготовительную работу: | |
<?php | |
// вот эти все хитрые штуки нужны, чтобы сделать из isNewRecord такую запись, как будто | |
// она была из БД, чтобы отработал нормально save() | |
$id = ...; // ID существующей в БД записи | |
$new->setIsNewRecord(false); | |
$new->setOldAttributes(['id' => $id]); | |
$new->id = $id; | |
// и теперь можно сохранять | |
$new->save(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment