Skip to content
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
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
```


Expand Down
5 changes: 5 additions & 0 deletions src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
24 changes: 24 additions & 0 deletions src/WhereNotInClause.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace WPQueryBuilder;

class WhereNotInClause implements WhereClause {

private $bindings;
private $column;

public function __construct($column, $values){
$this->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;
}

}
13 changes: 13 additions & 0 deletions tests/UnitTests/WhereTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;",
Expand Down