Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
FindOrCreate yii2 activerecord trait
<?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
You can’t perform that action at this time.