Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 save, check if exist, if yes give id back, if not, create (and give id back)

Tags:

save

exists

yii2

I wonder if there is a function in yii2 I imagine similar as save(), what would do the following: check if the given record exist in the db with these attributes, if yes, it would give back id, if not, it would create it and give back id. I think it would be cool. Probably there is something like that. Can you please help me where can I find it? Thank you!

like image 969
user2511599 Avatar asked Dec 04 '25 11:12

user2511599


2 Answers

I don't think there's that specific functionality but in addition to save, you can also use exists.

$exists = ModelName::find()->where( [ 'id' => 1 ] )->exists();

if($exists) {
  //it exists

} else {
  //doesn't exist so create record

}
like image 197
Coz Avatar answered Dec 07 '25 16:12

Coz


$model = ModelName::findOne(1) ?? new ModelName();
//or 
$model = ModelName::find()->where(['id' => 1])->one() ?? new ModelName();
  1. if 'id' is primapy key
  2. if not
like image 27
Gosha Say Avatar answered Dec 07 '25 18:12

Gosha Say