Skip to content

Commit 21f4d19

Browse files
Anton Komarevtaylorotwell
authored andcommitted
Add whereKeyNot to Eloquent Builder (#20817)
1 parent 418d5f6 commit 21f4d19

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Illuminate/Database/Eloquent/Builder.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,23 @@ public function whereKey($id)
190190
return $this->where($this->model->getQualifiedKeyName(), '=', $id);
191191
}
192192

193+
/**
194+
* Add a where clause on the primary key to the query.
195+
*
196+
* @param mixed $id
197+
* @return $this
198+
*/
199+
public function whereKeyNot($id)
200+
{
201+
if (is_array($id) || $id instanceof Arrayable) {
202+
$this->query->whereNotIn($this->model->getQualifiedKeyName(), $id);
203+
204+
return $this;
205+
}
206+
207+
return $this->where($this->model->getQualifiedKeyName(), '!=', $id);
208+
}
209+
193210
/**
194211
* Add a basic where clause to the query.
195212
*

tests/Database/DatabaseEloquentBuilderTest.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,45 @@ public function testWhereKeyMethodWithCollection()
914914
$builder->whereKey($collection);
915915
}
916916

917+
public function testWhereKeyNotMethodWithInt()
918+
{
919+
$model = $this->getMockModel();
920+
$builder = $this->getBuilder()->setModel($model);
921+
$keyName = $model->getQualifiedKeyName();
922+
923+
$int = 1;
924+
925+
$builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', $int);
926+
927+
$builder->whereKeyNot($int);
928+
}
929+
930+
public function testWhereKeyNotMethodWithArray()
931+
{
932+
$model = $this->getMockModel();
933+
$builder = $this->getBuilder()->setModel($model);
934+
$keyName = $model->getQualifiedKeyName();
935+
936+
$array = [1, 2, 3];
937+
938+
$builder->getQuery()->shouldReceive('whereNotIn')->once()->with($keyName, $array);
939+
940+
$builder->whereKeyNot($array);
941+
}
942+
943+
public function testWhereKeyNotMethodWithCollection()
944+
{
945+
$model = $this->getMockModel();
946+
$builder = $this->getBuilder()->setModel($model);
947+
$keyName = $model->getQualifiedKeyName();
948+
949+
$collection = new Collection([1, 2, 3]);
950+
951+
$builder->getQuery()->shouldReceive('whereNotIn')->once()->with($keyName, $collection);
952+
953+
$builder->whereKeyNot($collection);
954+
}
955+
917956
protected function mockConnectionForModel($model, $database)
918957
{
919958
$grammarClass = 'Illuminate\Database\Query\Grammars\\'.$database.'Grammar';

0 commit comments

Comments
 (0)