From 3f1c0c144cc5c25129f662e0fea95b91e8bd03d2 Mon Sep 17 00:00:00 2001 From: Gregory Letellier Date: Fri, 27 Oct 2023 10:02:16 +0200 Subject: [PATCH] =?UTF-8?q?valeur=20par=20d=C3=A9faut=20pour=20le=20pk=20d?= =?UTF-8?q?ans=20le=20querybuilder,=20ajout=20du=20whereRaw=20sur=20le=20m?= =?UTF-8?q?odel,=20fixation=20=C3=A0=20*=20sur=20la=20liste=20de=20colonne?= =?UTF-8?q?s=20si=20non=20d=C3=A9finie?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/QueryBuilder.php | 26 ++++++++++++++++++++++---- tests/DbTest.php | 12 +++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/QueryBuilder.php b/src/QueryBuilder.php index b1632f2..349ac6d 100644 --- a/src/QueryBuilder.php +++ b/src/QueryBuilder.php @@ -14,7 +14,7 @@ class QueryBuilder protected ?int $offset; protected string $raw_query; - public function __construct($table, $pk) + public function __construct($table, $pk = "id") { $this->table = $table; $this->pk = $pk; @@ -83,6 +83,12 @@ class QueryBuilder return $this; } + public function whereRaw(string $raw) + { + $this->wheres[] = $raw; + return $this; + } + public function find($id): mixed { $this->reset(); @@ -153,12 +159,24 @@ class QueryBuilder $ret->setQuery(""); $ret->setData([]); + if (count($this->columns) == 0) { + $this->columns("*"); + } + $columns = implode(",", $this->columns); $where = ""; foreach ($this->wheres as $expression) { - $sw = $expression->raw(); - $ret->addData($expression->getValue()); - if ($where != "") { + $sw = ""; + if ($expression instanceof Expression) { + $sw = $expression->raw(); + $ret->addData($expression->getValue()); + } + if ($expression instanceof string) { + if (trim($expression) !== "") { + $sw = "(" . $expression . ")"; + } + } + if ($where != "" && $sw != "") { $where .= " AND "; } $where .= $sw; diff --git a/tests/DbTest.php b/tests/DbTest.php index 90762eb..fa26128 100644 --- a/tests/DbTest.php +++ b/tests/DbTest.php @@ -23,7 +23,7 @@ test("insert row",function () { }); test("querybuilder", function() { - $qb = new QueryBuilder("test","id"); + $qb = new QueryBuilder("test"); $row = $qb->find(1); expect($row)->toBeObject(); @@ -41,6 +41,16 @@ test("querybuilder", function() { expect($rows)->toBeArray(); expect(count($rows))->toBe(0); + + $qb->reset(); + $rows = $qb->whereRaw("id = 1")->columns("*")->get(); + expect($rows)->toBeArray(); + expect(count($rows))->toBe(1); + + $qb->reset(); + $rows = $qb->whereRaw("id = 1")->get(); + expect($rows)->toBeArray(); + expect(count($rows))->toBe(1); }); test("update row", function() {