Last active
June 26, 2018 04:37
-
-
Save m8rge/578b9a497b3eb937d3f5 to your computer and use it in GitHub Desktop.
FindOrCreate yii2 activerecord trait
This file contains 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
<?php | |
namespace common\traits; | |
trait FindOrCreate | |
{ | |
/** | |
* @param mixed $key Primary key or array with condition for \yii\db\Query::where(condition) | |
* @return static | |
* @throws \Exception | |
*/ | |
public static function findOrCreate($key): self | |
{ | |
if (is_array($key)) { | |
$condition = $key; | |
} else { | |
$fieldName = static::getTableSchema()->primaryKey; | |
if (count($fieldName) > 1) { | |
throw new \RuntimeException('Composite keys doesn\'t support'); | |
} | |
$fieldName = reset($fieldName); | |
$condition = [$fieldName => $key]; | |
} | |
/** @noinspection PhpUndefinedMethodInspection */ | |
$model = static::find()->where($condition)->one(); | |
/** @noinspection PhpMethodParametersCountMismatchInspection */ | |
return $model ?? new static($condition); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment