Skip to content

Commit

Permalink
Update docs about hasMetaLike()
Browse files Browse the repository at this point in the history
  • Loading branch information
bluehaoran authored Nov 26, 2018
1 parent 8c3ad95 commit 108d63c
Showing 1 changed file with 22 additions and 5 deletions.
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');
```

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

0 comments on commit 108d63c

Please sign in to comment.