diff --git a/Database/Traits/CaseWhen.php b/Database/Traits/CaseWhen.php new file mode 100644 index 00000000..a40313d9 --- /dev/null +++ b/Database/Traits/CaseWhen.php @@ -0,0 +1,79 @@ +_condition[] = 'CASE ' . $column; + } + + + /** + * @param array|string $condition + * @param string $then + * @return $this + * @throws Exception + */ + public function when(array|string $condition, string $then): static + { + $this->_condition[] = sprintf('WHEN %s THEN %s', $this->activeQuery->makeNewSqlGenerate() + ->where($condition) + ->getCondition(), $then); + + return $this; + } + + + /** + * @param string $alias + */ + public function else(string $alias) + { + $this->else = $alias; + } + + + /** + * @return string + */ + #[Pure] public function end(): string + { + if (empty($this->_condition)) { + return ''; + } + $prefix = implode(' ', $this->_condition); + if (!empty($this->else)) { + $prefix .= ' ELSE ' . $this->else; + } + return $prefix . ' END'; + } + +} diff --git a/Database/Traits/QueryTrait.php b/Database/Traits/QueryTrait.php index 9aaefbc5..9efbfc46 100644 --- a/Database/Traits/QueryTrait.php +++ b/Database/Traits/QueryTrait.php @@ -15,6 +15,10 @@ use Database\ActiveRecord; use Database\Condition\MathematicsCondition; use Database\Sql; use Exception; +use JetBrains\PhpStorm\Pure; +use ReflectionException; +use Snowflake\Exception\NotFindClassException; +use Snowflake\Snowflake; /** * Trait QueryTrait @@ -58,6 +62,17 @@ trait QueryTrait } + /** + * @param string $column + * @param callable $callable + * @return CaseWhen + */ + public function case(string $column, callable $callable): CaseWhen + { + return call_user_func($callable, new CaseWhen($column, $this)); + } + + /** * @param $condition * @param $condition1 @@ -678,6 +693,17 @@ trait QueryTrait } + /** + * @return Sql + * @throws ReflectionException + * @throws NotFindClassException + */ + public function makeNewSqlGenerate(): Sql + { + return Snowflake::createObject(Sql::class); + } + + /** * @param $columns * @param $value