From f84b396049a447a8c26309333d7ee494dd2dbcfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mr=C2=B7x?= Date: Wed, 31 Mar 2021 01:54:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Database/ActiveRecord.php | 49 ++++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/Database/ActiveRecord.php b/Database/ActiveRecord.php index 7f5c0b88..43c5380a 100644 --- a/Database/ActiveRecord.php +++ b/Database/ActiveRecord.php @@ -129,15 +129,7 @@ class ActiveRecord extends BaseActiveRecord if (empty($attributes)) { return \logger()->addError(FIND_OR_CREATE_MESSAGE, 'mysql'); } - - $className = get_called_class(); - - /** @var Channel $channel */ - $channel = Snowflake::app()->get('channel'); - $select = $channel->pop($className, function () use ($className) { - return new $className(); - }); - + $select = self::getModelClass(); $select->attributes = $attributes; if (!$select->save()) { return \logger()->addError($select->getLastError(), 'mysql'); @@ -146,6 +138,45 @@ class ActiveRecord extends BaseActiveRecord } + /** + * @param array $condition + * @param array $attributes + * @return bool|static + * @throws Exception + */ + public static function updateOrCreate(array $condition, array $attributes = []): bool|static + { + if (empty($attributes)) { + return \logger()->addError(FIND_OR_CREATE_MESSAGE, 'mysql'); + } + /** @var static $select */ + $select = static::find()->where($condition)->first(); + if (empty($select)) { + $select = self::getModelClass(); + } + $select->attributes = $attributes; + if (!$select->save()) { + return \logger()->addError($select->getLastError(), 'mysql'); + } + return $select; + } + + + /** + * @return static + * @throws Exception + */ + private static function getModelClass(): static + { + $className = get_called_class(); + /** @var Channel $channel */ + $channel = Snowflake::app()->get('channel'); + return $channel->pop($className, function () use ($className) { + return new $className(); + }); + } + + /** * @param $action * @param $columns