diff --git a/CHANGELOG.md b/CHANGELOG.md index e9f44cc..4554e2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Release Notes for Entry Meta +## 3.1.0 - 2022-11-21 +### Added +- Added existence filters + ## 3.0.2 - 2022-08-31 ### Fixed - Fixed validation message diff --git a/README.md b/README.md index 357d7f4..e5919c2 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ Or using Twig: You can query by metadata on the active record class (e.g `craft\records\Entry`) using the following methods: #### Filter by metadata +##### Value ```php Entry::find()->whereMetadata('foo','bar'); ``` @@ -113,6 +114,23 @@ The method defaults to the `=` operand, which you can override on the third argu ```php Entry::find()->whereMetadata('views',0,'>'); ``` +##### Existence +You can also check for existence of metadata **keys**: +```php +Entry::find()->hasMetadata('foo'); +``` +Or, conversely: +```php +Entry::find()->doesntHaveMetadata('foo'); +``` +To filter down by the existence of metadata itself, simply omit the key argument: +```php +Entry::find()->hasMetadata(); +``` +or +```php +Entry::find()->doesntHaveMetadata(); +``` #### Sort by metadata ```php Entry::find()->whereMetadata('views',0,'>')->orderByMetadata('views',false, true); diff --git a/src/behaviors/ActiveQueryBehavior.php b/src/behaviors/ActiveQueryBehavior.php index f9351ae..b1bd617 100644 --- a/src/behaviors/ActiveQueryBehavior.php +++ b/src/behaviors/ActiveQueryBehavior.php @@ -45,6 +45,14 @@ public function orderByMetadata($key, $asc = true, $numeric = false) return $this->owner->orderBy([$keyExpression => $dir]); } + public function hasMetadata($key = null) { + return $this->_whereMetadata($key,null,' IS NOT ','where'); + } + + public function doesntHaveMetadata($key = null) { + return $this->_whereMetadata($key,null,' IS ','where'); + } + private function _whereMetadata($key, $value, $operand, $method) { return $this->owner->{$method}($this->_getCondition($key, $value, $operand)); @@ -75,9 +83,14 @@ private function _getCondition($key, $value, $operand): string } } - private function _getKeyExpression($key, $cast = null) + private function _getKeyExpression($key, $cast = null): string { $column = EntryMeta::COLUMN_NAME; + + if (is_null($key)) { + return $column; + } + $Key = $this->_transformKey($key); if ($this->dbDriver === self::MYSQL) { @@ -99,6 +112,10 @@ private function _getKeyExpression($key, $cast = null) private function _transformValue($value) { + if (is_null($value)) { + return 'NULL'; + } + if (is_bool($value)) { return $value ? 'true' : 'false'; }