From 3a6bf69866ccce0fce76eec7cdb43bf7fa979217 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mr=C2=B7x?= Date: Thu, 10 Sep 2020 16:22:31 +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 | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Database/ActiveRecord.php b/Database/ActiveRecord.php index 4215ed37..80cfc761 100644 --- a/Database/ActiveRecord.php +++ b/Database/ActiveRecord.php @@ -12,6 +12,8 @@ namespace Database; use Exception; use Database\Base\BaseActiveRecord; use Snowflake\Core\ArrayAccess; +use Snowflake\Error\Logger; +use Snowflake\Snowflake; defined('SAVE_FAIL') or define('SAVE_FAIL', 3227); @@ -101,6 +103,28 @@ class ActiveRecord extends BaseActiveRecord } + /** + * @param $attributes + * @param $condition + * @return bool|ActiveRecord|mixed + * @throws Exception + */ + public static function findOrCreate(array $condition, array $attributes = []) + { + $select = static::find()->where($condition)->first(); + if (!empty($select)) { + return $select; + } + if (empty($attributes)) { + $message = 'Create a new model, but the data cannot be empty.'; + return Snowflake::app()->logger->addError($message, 'mysql'); + } + $select = new static(); + $select->attributes = $attributes; + return $select->save(); + } + + /** * @param $action * @param $columns