Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active June 26, 2018 04:37
Show Gist options
  • Save m8rge/578b9a497b3eb937d3f5 to your computer and use it in GitHub Desktop.
Save m8rge/578b9a497b3eb937d3f5 to your computer and use it in GitHub Desktop.
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