You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- Extract SelectIteratorTrait from SelectIterator
- Check flattenFields more thoroughly, and remove it in some
parts where it is not allowed anymore
- Improve documentation with more examples
@@ -186,7 +186,7 @@ This would be aquivalent to this string SELECT query (when using MySQL):
186
186
$selectStatement = $db->select('SELECT `fufumama`,`b`.`lalala`,`a`.`setting_value` AS "result",(`a`.`setting_value`+`b`.`blabla_value`) AS "result2" FROM `blobs`.`aa_sexy` `a`,`blobs`.`aa_blubli` `b` LEFT JOIN `blobs`.`aa_blubla` `c` ON (`c`.`field` = `b`.`field5` AND `b`.`sexy` = ?) WHERE (`a`.`field` = `b`.`field`) AND `setting_id`=? AND `boring_field_name` IN (?,?,?,?) AND (`setting_value` = ? OR `setting_value2` = ?) GROUP BY `a`.`field` ORDER BY `a`.`field` DESC LIMIT 10 OFFSET 5 FOR UPDATE', [5,'orders_xml_override',5,3,8,13,'one','two']);
187
187
```
188
188
189
-
Important parts of how the conversion works:
189
+
#### Important conversion details:
190
190
191
191
- If an expression contains something like :fieldname: it is assumed that it is a field or table name which will then be escaped. For simple WHERE restrictions or fields definitions field names are escaped automatically.
192
192
- You can use "field" if there is just one field, or "fields" for multiple fields. The same with "table" and "tables".
@@ -497,9 +497,7 @@ DBBuilderInterface offers the following functions:
497
497
498
498
All except the last two return a builder object which helps you easily create a query and get the results. Compared to DBInterface you do not have to remember what data can be contained in a structured query - your IDE will suggest whatever is available. You can also have a look at the builder objects themselves - they are all very short.
499
499
500
-
It is almost easiest to just try it out yourself - in the background DBBuilder converts the query into a structured query to pass to DBInterface.
501
-
502
-
There are some examples below for each of the 6 builder functions:
500
+
Looking at some examples should make the usage quite clear - here are some for each of the 6 builder functions:
503
501
504
502
### Count
505
503
@@ -521,6 +519,42 @@ An easy way to just count the number of rows.
521
519
522
520
### Select
523
521
522
+
Select queries can become the most complex, so they have many options - here is an example with all of them (many are optional though!):
The above query takes advantage that each SELECT query builder can be iterated over. As soon as the foreach loop starts the query is executed and one entry after the other is retrieved.
555
+
556
+
If you want to retrieve all results at once (because you know you need them anyway), this is another option:
Select queries can become the most complex, so they have many options - above you can see all of them, except for the last call, where you have different options:
589
+
Or if you only need one entry:
552
590
553
-
- getAllEntries, to retrieve an array with all the entries at once
554
-
- getOneEntry, to just get exactly one entry
555
-
- getIterator, to get an object you can iterate over (foreach) so you can get one result after the other
556
-
- getFlattenedFields, which means the results are "flattened"
Note that you can use `field` instead of `fields` and `inTable` instead of `inTables` if you want to pass only one value (as a string), and that you can pass a string to `groupBy` and `orderBy` if you only want to use one string value.
621
+
622
+
There are four options to get the data from a select query builder:
557
623
558
-
getFlattenedFields can be useful for something like this:
624
+
-**getIterator**, to get an object you can iterate over (foreach) so you can get one result after the other - this is implicitely used in the first example by putting the builder into the foreach loop, as the builder implements IteratorAggregate
625
+
-**getAllEntries**, to retrieve an array with all the entries at once, which was the second example
626
+
-**getOneEntry**, to just get exactly one entry, used in the third example
627
+
-**getFlattenedFields**, which means the results are "flattened"
628
+
629
+
`getFlattenedFields` can be useful for something like this:
559
630
560
631
```php
561
632
$userIds = $dbBuilder
@@ -566,14 +637,18 @@ $userIds = $dbBuilder
566
637
'u.zipCode' => 33769,
567
638
])
568
639
->getFlattenedFields();
640
+
641
+
foreach ($userIds as $userId) {
642
+
// Do something which each $userId here
643
+
}
569
644
```
570
645
571
646
Instead of a list of arrays each with a field "userId", the results are flattened and directly return a list of user IDs. Flattening is mostly useful for IDs or other simple lists of values, where you just need one array instead of an array of an array.
572
647
573
648
### Insert
574
649
575
650
```php
576
-
$newUserId = $dbBuilder
651
+
$newUserIdFromDatabase = $dbBuilder
577
652
->insert()
578
653
->inTable('users')
579
654
->set([
@@ -603,7 +678,7 @@ $rowsAffected = $dbBuilder
603
678
->writeAndReturnAffectedNumber();
604
679
```
605
680
606
-
You can use `writeAndReturnAffectedNumber` if you are interested in the number of affected/changed rows, or `write` if you do not need that information. Another optionsnot shown above is `orderBy`.
681
+
You can use `writeAndReturnAffectedNumber` if you are interested in the number of affected/changed rows, or `write` if you do not need that information. Another option which is not shown above is `orderBy`.
607
682
608
683
### Insert or Update
609
684
@@ -647,6 +722,67 @@ You can use `writeAndReturnAffectedNumber` if you are interested in the number o
647
722
648
723
The transaction function works the same as the one in DBInterface - in fact, DBBuilderInterface just passes it as-is to DBInterface.
649
724
725
+
### General syntax rules
726
+
727
+
For simple column names to values within any queries, you can just use the name to value syntax like you do in PHP:
728
+
729
+
```php
730
+
$user = $dbBuilder
731
+
->select()
732
+
->inTable('users')
733
+
->where([
734
+
'user_id' => $userId, // user_id must be equal to $userId
735
+
])
736
+
->getOneEntry();
737
+
738
+
// $user now contains all table column and values:
739
+
echo $user['user_id'];
740
+
```
741
+
742
+
The values are separated from the query to ensure safety, and the table names and column names are quoted for you.
743
+
744
+
If you want to use more complex expressions, you are free to do so:
745
+
746
+
```php
747
+
$user = $dbBuilder
748
+
->select()
749
+
->inTable('users')
750
+
->where([
751
+
':user_id: BETWEEN ? AND ?' => [15, 55],
752
+
':create_date: > ?' => time() - 86400,
753
+
])
754
+
->getOneEntry();
755
+
```
756
+
757
+
In these cases make sure to surround all table column names / field names and table names with colons, so the library can escape them. You can use any SQL syntax you want, and each entry in a WHERE clause is connected by AND - so the WHERE part is converted to the following by the library:
758
+
759
+
```sql
760
+
... WHERE (`user_id` BETWEEN ? AND ?) AND (`create_date`> ?) ...
761
+
```
762
+
763
+
For custom expressions every expression is surrounded by brackets, to make sure they do not influence each other, and the parameters are sent separately from the query, in this case: `[15, 55, time() - 86400]`
764
+
765
+
This syntax is used consistently for any data passed to the library, and where that type of syntax can be translated to valid SQL. So an UPDATE query could look like this:
766
+
767
+
```php
768
+
$rowsAffected = $dbBuilder
769
+
->update()
770
+
->inTable('users')
771
+
->set([
772
+
'last_login_date' => time(),
773
+
':visits: = :visits: + 1',
774
+
':full_name: = CONCAT(:first_name:,:last_name:)',
775
+
':balance: = :balance: + ?' => $balanceIncrease,
776
+
])
777
+
->where([
778
+
'user_id' => 33,
779
+
':last_login_date: < ?' => time()-86400,
780
+
])
781
+
->writeAndReturnAffectedNumber();
782
+
```
783
+
784
+
This should make it easy to read and write queries, even if you don't know much SQL, and you don't have to think about separating the query and the parameters yourself - the library is doing it for you.
0 commit comments