valeur par défaut pour le pk dans le querybuilder, ajout du whereRaw sur le model, fixation à * sur la liste de colonnes si non définie

This commit is contained in:
Gregory Letellier
2023-10-27 10:02:16 +02:00
parent a7d63c8c07
commit 3f1c0c144c
2 changed files with 33 additions and 5 deletions

View File

@@ -14,7 +14,7 @@ class QueryBuilder
protected ?int $offset; protected ?int $offset;
protected string $raw_query; protected string $raw_query;
public function __construct($table, $pk) public function __construct($table, $pk = "id")
{ {
$this->table = $table; $this->table = $table;
$this->pk = $pk; $this->pk = $pk;
@@ -83,6 +83,12 @@ class QueryBuilder
return $this; return $this;
} }
public function whereRaw(string $raw)
{
$this->wheres[] = $raw;
return $this;
}
public function find($id): mixed public function find($id): mixed
{ {
$this->reset(); $this->reset();
@@ -153,12 +159,24 @@ class QueryBuilder
$ret->setQuery(""); $ret->setQuery("");
$ret->setData([]); $ret->setData([]);
if (count($this->columns) == 0) {
$this->columns("*");
}
$columns = implode(",", $this->columns); $columns = implode(",", $this->columns);
$where = ""; $where = "";
foreach ($this->wheres as $expression) { foreach ($this->wheres as $expression) {
$sw = $expression->raw(); $sw = "";
$ret->addData($expression->getValue()); if ($expression instanceof Expression) {
if ($where != "") { $sw = $expression->raw();
$ret->addData($expression->getValue());
}
if ($expression instanceof string) {
if (trim($expression) !== "") {
$sw = "(" . $expression . ")";
}
}
if ($where != "" && $sw != "") {
$where .= " AND "; $where .= " AND ";
} }
$where .= $sw; $where .= $sw;

View File

@@ -23,7 +23,7 @@ test("insert row",function () {
}); });
test("querybuilder", function() { test("querybuilder", function() {
$qb = new QueryBuilder("test","id"); $qb = new QueryBuilder("test");
$row = $qb->find(1); $row = $qb->find(1);
expect($row)->toBeObject(); expect($row)->toBeObject();
@@ -41,6 +41,16 @@ test("querybuilder", function() {
expect($rows)->toBeArray(); expect($rows)->toBeArray();
expect(count($rows))->toBe(0); 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() { test("update row", function() {