From b99d28a51585d73b75405774030dc910a517a7dc Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 27 Apr 2024 23:33:25 +0300 Subject: [PATCH] add WhereNotIn clause #7 --- README.md | 8 ++++---- src/Query.php | 5 +++++ src/WhereNotInClause.php | 24 ++++++++++++++++++++++++ tests/UnitTests/WhereTest.php | 13 +++++++++++++ 4 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 src/WhereNotInClause.php diff --git a/README.md b/README.md index 21fd819..58a8363 100644 --- a/README.md +++ b/README.md @@ -112,13 +112,13 @@ $qb->select()->from("wp_users")->whereIn("ID", [1, 2, 3])->get(); //SELECT * FROM wp_users WHERE ID IN (1, 2, 3); ``` -### Where column value IN +### Where column value NOT IN -Adds a `WHERE` clause, matching records which have a column value in the array provided: +Adds a `WHERE` clause by matching records that do not have a column value in the provided array: ```php -$qb->select()->from("wp_users")->whereIn("ID", [1, 2, 3])->get(); -//SELECT * FROM wp_users WHERE ID IN (1, 2, 3); +$qb->select()->from("wp_users")->whereNotIn("ID", [1, 2, 3])->get(); +//SELECT * FROM wp_users WHERE ID NOT IN (1, 2, 3); ``` diff --git a/src/Query.php b/src/Query.php index 2ad2d9e..08b979a 100644 --- a/src/Query.php +++ b/src/Query.php @@ -252,6 +252,11 @@ public function whereIn($column, $values) { return $this; } + public function whereNotIn($column, $values) { + $this->wheres->andWhere(new WhereNotInClause($column,$values)); + return $this; + } + public function search($fieldOrFields, $searchTerm){ $search = new CompositeWhereClause(); $fields = is_array($fieldOrFields) ? $fieldOrFields : [$fieldOrFields]; diff --git a/src/WhereNotInClause.php b/src/WhereNotInClause.php new file mode 100644 index 0000000..14b3489 --- /dev/null +++ b/src/WhereNotInClause.php @@ -0,0 +1,24 @@ +column = $column; + $this->bindings = $values; + } + + public function buildSql() { + $inList = '(' . implode(', ', array_fill(0, count($this->bindings), '%s')) . ')'; + return implode(' ', [$this->column, "NOT IN", $inList]); + } + + public function getBindings(){ + return $this->bindings; + } + +} \ No newline at end of file diff --git a/tests/UnitTests/WhereTest.php b/tests/UnitTests/WhereTest.php index 5469c12..296a9e8 100644 --- a/tests/UnitTests/WhereTest.php +++ b/tests/UnitTests/WhereTest.php @@ -224,6 +224,19 @@ public function testWithWhereInCondition(){ ->get(); } + public function testWithWhereNotInCondition(){ + $this->wpdb->expects($this->once())->method('prepare')->with( + "SELECT * FROM tablename WHERE field NOT IN (%s, %s, %s);", + ['foo', 'bar', 'baz'] + ); + + $qb = new Query($this->wpdb); + $qb->select() + ->from("tablename") + ->whereNotIn("field", ['foo', 'bar', 'baz']) + ->get(); + } + public function testSearchSingleColumn(){ $this->wpdb->expects($this->once())->method('prepare')->with( "SELECT * FROM tablename WHERE (field LIKE %s) AND field2 = %s;",