Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow searching meta fields by LIKE. #430

Merged
merged 7 commits into from
Nov 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,15 +259,22 @@ $trueOrFalse = $post->saveMeta('foo', 'baz'); // boolean

### Querying Posts by Custom Fields (Meta)

There are multiples possibilities to query posts by their custom fields (meta). Just use the `hasMeta()` scope under `Post` (actually for all models using the `HasMetaFields` trait) class:
There are multiples possibilities to query posts by their custom fields (meta) by using scopes on a `Post` (or another other model which uses the `HasMetaFields` trait) class:

To check if a meta key exists, use the `hasMeta()` scope:
```
// Finds a published post with a meta flag.
$post = Post::published()->hasMeta('featured_article')->first();
```

If you want to precisely match a meta-field, you can use the `hasMeta()` scope with a value.

```php
// Using just one custom field
$post = Post::published()->hasMeta('username', 'jgrossi')->first(); // setting key and value
$post = Post::published()->hasMeta('username'); // setting just the key
// Find a published post which matches both meta_key and meta_value.
$post = Post::published()->hasMeta('username', 'jgrossi')->first();
```

You can also use the `hasMeta()` scope passing an array as parameter:
If you need to match multiple meta-fields, you can also use the `hasMeta()` scope passing an array as parameter:

```php
$post = Post::hasMeta(['username' => 'jgrossi'])->first();
Expand All @@ -276,6 +283,16 @@ $post = Post::hasMeta(['username' => 'jgrossi', 'url' => 'jgrossi.com'])->first(
$post = Post::hasMeta(['username', 'url'])->first();
```

If you need to match a case-insensitive string, or match with wildcards, you can use the `hasMetaLike()` scope with a value. This uses an SQL `LIKE` operator, so use '%' as a wildcard operator.

```php
// Will match: 'J Grossi', 'J GROSSI', and 'j grossi'.
$post = Post::published()->hasMetaLike('author', 'J GROSSI')->first();

// Using % as a wildcard will match: 'J Grossi', 'J GROSSI', 'j grossi', 'Junior Grossi' etc.
$post = Post::published()->hasMetaLike('author', 'J%GROSSI')->first();
```

### Fields Aliases

The `Post` class has support to "aliases", so if you check the `Post` class you should note some aliases defined in the static `$aliases` array, like `title` for `post_title` and `content` for `post_content`.
Expand Down
37 changes: 23 additions & 14 deletions src/Concerns/MetaFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

namespace Corcel\Concerns;

use Corcel\Model\Meta\PostMeta;
use Corcel\Model\Post;
use Illuminate\Database\Eloquent\Builder;
use ReflectionClass;
use UnexpectedValueException;

/**
Expand All @@ -21,9 +18,9 @@ trait MetaFields
*/
protected $builtInClasses = [
\Corcel\Model\Comment::class => \Corcel\Model\Meta\CommentMeta::class,
\Corcel\Model\Post::class => \Corcel\Model\Meta\PostMeta::class,
\Corcel\Model\Term::class => \Corcel\Model\Meta\TermMeta::class,
\Corcel\Model\User::class => \Corcel\Model\Meta\UserMeta::class,
\Corcel\Model\Post::class => \Corcel\Model\Meta\PostMeta::class,
\Corcel\Model\Term::class => \Corcel\Model\Meta\TermMeta::class,
\Corcel\Model\User::class => \Corcel\Model\Meta\UserMeta::class,
];

/**
Expand Down Expand Up @@ -86,30 +83,42 @@ protected function getMetaForeignKey()
* @param Builder $query
* @param string $meta
* @param mixed $value
* @param string $operator
* @return Builder
*/
public function scopeHasMeta(Builder $query, $meta, $value = null)
public function scopeHasMeta(Builder $query, $meta, $value = null, string $operator = '=')
{
if (!is_array($meta)) {
$meta = [$meta => $value];
}

foreach ($meta as $key => $value) {
$query->whereHas('meta', function ($query) use ($key, $value) {
if (is_string($key)) {
$query->where('meta_key', $key);

return is_null($value) ? $query : // 'foo' => null
$query->where('meta_value', $value); // 'foo' => 'bar'
$query->whereHas('meta', function (Builder $query) use ($key, $value, $operator) {
if (!is_string($key)) {
return $query->where('meta_key', $operator, $value);
}
$query->where('meta_key', $operator, $key);

return $query->where('meta_key', $value); // 0 => 'foo'
return is_null($value) ? $query :
$query->where('meta_value', $operator, $value);
});
}

return $query;
}

/**
* @param Builder $query
* @param string $meta
* @param mixed $value
* @return Builder
*/
public function scopeHasMetaLike(Builder $query, $meta, $value = null)
{
return $this->scopeHasMeta($query, $meta, $value, 'like');
}


/**
* @param string $key
* @param mixed $value
Expand Down
50 changes: 50 additions & 0 deletions tests/Unit/Traits/HasMetaFieldsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,54 @@ public function it_can_get_meta_data_from_get_meta_method()

$this->assertEquals('bar', $user->getMeta('foo'));
}

/**
* @test
*/
public function it_can_check_meta_using_has_meta_method()
{
factory(User::class)->create()->createMeta(['foo' => 'ba']);
factory(User::class)->create()->createMeta(['foo' => 'bar']);
factory(User::class)->create()->createMeta(['foo' => 'baz']);
factory(User::class)->create()->createMeta(['foo' => 'BA']);

/** @var Collection $users */
$users = User::hasMeta(['foo' => 'ba'])->get();

$this->assertInstanceOf(Collection::class, $users);
$this->assertEquals(1, $users->count());
}

/**
* @test
*/
public function it_can_find_users_by_meta_like_after_creating_meta()
{
factory(User::class)->create()->createMeta(['foo' => 'ba']);
factory(User::class)->create()->createMeta(['foo' => 'bar']);
factory(User::class)->create()->createMeta(['foo' => 'baz']);
factory(User::class)->create()->createMeta(['foo' => 'BA']);

/** @var Collection $users */
$users = User::hasMetaLike(['foo' => 'ba'])->get();

$this->assertInstanceOf(Collection::class, $users);
$this->assertEquals(2, $users->count());
}

/**
* @test
*/
public function it_can_find_users_by_meta_like_with_wildcard_after_creating_meta()
{
factory(User::class)->create()->createMeta(['foo' => 'ba']);
factory(User::class)->create()->createMeta(['foo' => 'bar']);
factory(User::class)->create()->createMeta(['foo' => 'baz']);

/** @var Collection $users */
$users = User::hasMetaLike(['foo' => 'ba%'])->get();

$this->assertInstanceOf(Collection::class, $users);
$this->assertEquals(3, $users->count());
}
}