diff --git a/README.md b/README.md index 91deef8..2f2df05 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,13 @@ If you only want to search on a single custom attribute, you can use the modelSc $yourModel->withExtraAttributes('name', 'value')->get(); ``` +Also, if you only want to search on a single custom attribute with a custom operator, you can use the modelScope like this + +```php +// returns all models that have a schemaless attribute `name` starting with `value` +$yourModel->withExtraAttributes('name', 'LIKE', 'value%')->get(); +``` + If you only want to search on a nested custom attribute, you can use the modelScope like this ```php diff --git a/src/SchemalessAttributes.php b/src/SchemalessAttributes.php index bcc1c90..cfd7f18 100644 --- a/src/SchemalessAttributes.php +++ b/src/SchemalessAttributes.php @@ -111,13 +111,18 @@ public function modelScope(): Builder [$builder, $schemalessAttributes] = $arguments; } - if (count($arguments) >= 3) { + if (count($arguments) === 3) { [$builder, $name, $value] = $arguments; $schemalessAttributes = [$name => $value]; } + if (count($arguments) >= 4) { + [$builder, $name, $operator, $value] = $arguments; + $schemalessAttributes = [$name => $value]; + } + foreach ($schemalessAttributes as $name => $value) { - $builder->where("{$this->sourceAttributeName}->{$name}", $value); + $builder->where("{$this->sourceAttributeName}->{$name}", $operator ?? '=', $value); } return $builder; diff --git a/tests/HasSchemalessAttributesTest.php b/tests/HasSchemalessAttributesTest.php index 557d801..7346633 100644 --- a/tests/HasSchemalessAttributesTest.php +++ b/tests/HasSchemalessAttributesTest.php @@ -274,16 +274,25 @@ public function it_has_a_scope_to_get_models_with_the_given_schemaless_attribute $model1 = TestModel::create(['schemaless_attributes' => [ 'name' => 'value', 'name2' => 'value2', + 'arr' => [ + 'subKey1' => 'subVal1' + ] ]]); $model2 = TestModel::create(['schemaless_attributes' => [ 'name' => 'value', 'name2' => 'value2', + 'arr' => [ + 'subKey1' => 'subVal1' + ] ]]); $model3 = TestModel::create(['schemaless_attributes' => [ 'name' => 'value', 'name2' => 'value3', + 'arr' => [ + 'subKey1' => 'subVal2' + ] ]]); $this->assertContainsModels([ @@ -306,7 +315,16 @@ public function it_has_a_scope_to_get_models_with_the_given_schemaless_attribute ], TestModel::withSchemalessAttributes('name', 'value')->get()); $this->assertContainsModels([ - ], TestModel::withSchemalessAttributes('name', 'non-existing-value')->get()); + $model1, $model2, + ], TestModel::withSchemalessAttributes('name2', '!=', 'value3')->get()); + + $this->assertContainsModels([ + $model3, + ], TestModel::withSchemalessAttributes('arr->subKey1', 'subVal2')->get()); + + $this->assertContainsModels([ + $model1, $model2, + ], TestModel::withSchemalessAttributes('arr->subKey1', '!=', 'subVal2')->get()); $this->assertContainsModels([ ], TestModel::withSchemalessAttributes('name', 'non-existing-value')->get());