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!
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
}
$model = ModelName::findOne(1) ?? new ModelName();
//or
$model = ModelName::find()->where(['id' => 1])->one() ?? new ModelName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With