feat: second int argument instead of assoc array for LIMIT and OFFSET (#32)

* feat: pass null to reset statements

* feat: limit offset as second argument

* fix(doc): change limit method in README
This commit is contained in:
Victor Westerlund 2024-01-12 13:24:04 +01:00 committed by GitHub
parent 5fefc5d19f
commit 17fa248edb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 13 deletions

View file

@ -260,14 +260,15 @@ Chain the `limit()` method before a `select()` statement to limit the amount of
```php
MySQL->limit(
int|array|null $limit
?int $limit,
?int $offset = null
): self;
```
> **Note**
> You can also flatten to a single dimensional array from the first entity by chaining [`MySQL->flatten()`](#flatten-array-to-single-dimension)
## Passing an integer to LIMIT
## Passing a single integer argument
This will simply `LIMIT` the results returned to the integer passed
```php
@ -282,11 +283,11 @@ $coffee = MySQL->for("beverages")->limit(1)->select(["beverage_name", "beverage_
]
```
## Passing an associative array to LIMIT
This will `OFFSET` and `LIMIT` the results returned from the first key of the array as `OFFSET` and the value of that key as `LIMIT`
## Passing two integer arguments
This will `OFFSET` and `LIMIT` the results returned. The first argument will be the `LIMIT` and the second argument will be its `OFFSET`.
```php
$coffee = MySQL->for("beverages")->limit([3 => 2])->select(["beverage_name", "beverage_size"]); // SELECT beverage_name, beverage_size FROM beverages LIMIT 3 OFFSET 2
$coffee = MySQL->for("beverages")->limit(3, 2)->select(["beverage_name", "beverage_size"]); // SELECT beverage_name, beverage_size FROM beverages LIMIT 3 OFFSET 2
```
```php
[

View file

@ -17,7 +17,7 @@
private ?string $order_by = null;
private ?string $filter_sql = null;
private array $filter_values = [];
private int|string|null $limit = null;
private ?string $limit = null;
// Pass constructor arguments to driver
function __construct() {
@ -150,8 +150,8 @@
return $this;
}
// Return SQL LIMIT string from integer or array of [offset => limit]
public function limit(int|array|null $limit): self {
// SQL LIMIT string
public function limit(?int $limit, ?int $offset = null): self {
// Unset row limit if null was passed
if ($limit === null) {
$this->limit = null;
@ -164,12 +164,13 @@
return $this;
}
// Use array key as LIMIT range start value
$offset = (int) array_keys($limit)[0];
// Use array value as LIMIT range end value
$limit = (int) array_values($limit)[0];
// No offset defined, set limit property directly as string
if (is_null($offset)) {
$this->limit = (string) $limit;
return $this;
}
// Set limit as SQL CSV
// Set limit and offset as SQL CSV
$this->limit = "{$offset},{$limit}";
return $this;
}