Skip to content

Commit fd9e349

Browse files
authored
Merge pull request #85 from pfwd/83-query-builder-find-all-by
Adding where clause
2 parents 21f8a4d + 68f6d1c commit fd9e349

File tree

3 files changed

+58
-3
lines changed

3 files changed

+58
-3
lines changed

src/DB/QueryBuilder.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,37 @@ public static function findAll(string $table)
8686
{
8787
return "SELECT * FROM `".$table."`";
8888
}
89+
90+
/**
91+
* @param array $conditions
92+
* @return string
93+
*/
94+
public static function where(array $conditions = []) {
95+
$sql ='';
96+
97+
$total = count($conditions);
98+
$num = 0;
99+
foreach($conditions as $field => $value) {
100+
$num ++;
101+
$sql.='`'.$field.'` =:'.$value;
102+
if($num < $total) {
103+
$sql.=' AND ';
104+
}
105+
106+
}
107+
108+
return $sql;
109+
}
110+
111+
/**
112+
* @param string $table
113+
* @param array $where
114+
* @return string
115+
*/
116+
public static function findAllBy(string $table, array $where = [])
117+
{
118+
$sql = "SELECT * FROM `".$table."` WHERE " .self::where($where);
119+
120+
return $sql;
121+
}
89122
}

src/Repository/Type/InvoiceItemRepository.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,21 @@ public function findAll(): array
6969

7070
}
7171

72+
/**
73+
* @param int $id
74+
* @return array
75+
*/
7276
public function findAllByInvoiceID(int $id):array
7377
{
7478
$results = [];
75-
$sql = QueryBuilder::findAllBy('invoice_item');
79+
$sql = QueryBuilder::findAllBy('invoice_item', [
80+
'invoice_id' => 'id'
81+
]);
7682

7783
$dbCon = $this->connection->open();
7884
$statement = $dbCon->prepare($sql);
7985
$statement->execute([
80-
'invoice_id' => $id
86+
'id' => $id
8187
]);
8288
$statement->execute();
8389
$rows = $statement->fetchAll();
@@ -87,7 +93,7 @@ public function findAllByInvoiceID(int $id):array
8793
$results[] = InvoiceItemHydrator::hydrate($row);
8894
}
8995
}
90-
96+
return $results;
9197
}
9298

9399
/**

tests/unit/DB/QueryBuilderTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,22 @@ public function testFindAll()
192192
$this->assertSame($expected, $sql);
193193
}
194194

195+
/**
196+
* @group entity
197+
* @group db
198+
* @group db-query-builder
199+
* @group db-query-builder-find-all-by
200+
*/
201+
public function testFindAllBy()
202+
{
203+
$sql = QueryBuilder::findAllBy('status', [
204+
'name' => 'name',
205+
'internal_name' => 'internal_name'
206+
]);
207+
$expected = "SELECT * FROM `status` WHERE `name` =:name AND `internal_name` =:internal_name";
208+
$this->assertSame($expected, $sql);
209+
}
210+
195211
protected function _before()
196212
{
197213
}

0 commit comments

Comments
 (0)