Skip to content

Commit

Permalink
add existence filters 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
matfish3 committed Nov 21, 2022
1 parent be0c412 commit 845d09f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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');
```
Expand All @@ -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);
Expand Down
19 changes: 18 additions & 1 deletion src/behaviors/ActiveQueryBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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) {
Expand All @@ -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';
}
Expand Down

0 comments on commit 845d09f

Please sign in to comment.