Skip to content
This repository has been archived by the owner on Nov 4, 2021. It is now read-only.

Usage scopes model #428

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,39 @@ App\MyModel::searchRaw([

This query will return raw response.


## Usage scopes model

When you have written a series of scope methods for your model and you want to use it in elastic, do it easily by adding a trait class.

Basic usage example:

```php
<?php

namespace App;

use ScoutElastic\ScopesModelHandleable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
use ScopesModelHandleable;

// You can set several scopes for one model. In this case, the first not empty result will be returned.
protected $scopesElastic = [
'scopePublished',
...
];

public function scopePublished($query)
{
return $query->where('has_published', true);
}

}
```

## Console commands

Available artisan commands are listed below:
Expand Down
39 changes: 39 additions & 0 deletions src/ScopesModelHandleable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace ScoutElastic;

use Illuminate\Support\Str;
use Laravel\Scout\Builder;
use ReflectionClass;

trait ScopesModelHandleable
{
public function initializeScopesModelHandleable()
{
$this->handleScopeMethods();
}

private function handleScopeMethods()
{
$context = $this;
$reflectionClass = new ReflectionClass(self::class);

if ($reflectionClass->hasProperty('scopesElastic')) {
foreach ($this->scopesElastic as $method) {
if ($reflectionClass->hasMethod($method)) {
$refMethod = $reflectionClass->getMethod($method);
$method = Str::of($method)->replaceFirst('scope', '')->camel()->__toString();

Builder::macro($method, function (...$args) use ($context, $refMethod) {
if (Str::is('scope*', $refMethod->getName())) {
$args[] = $this;
$args = array_reverse($args);

call_user_func_array([$context, $refMethod->getName()], $args);
}
});
}
}
}
}
}