Skip to content

Commit 01782a5

Browse files
committed
adding examples for subselect
1 parent 35b6eb1 commit 01782a5

File tree

1 file changed

+78
-1
lines changed

1 file changed

+78
-1
lines changed

docs/datamapper.md

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1975,7 +1975,7 @@ Additionally, the following methods allow you to reset specific areas of the que
19751975
- `resetFlags()` - Resets the `flags`
19761976

19771977
#### Subselect Objects
1978-
If you want to create a subselect, call the `subSelect()` method. When you are done building the subselect, give it an alias using the `asAlias()` method; the object itself can be used in the desired condition or expression.
1978+
If you want to create a subselect, call the `subSelect()` method. When you are done building the subselect, give it an alias using the `asAlias()` method; the object itself can be used in the desired condition or expression. When used in the `FROM` condition, you will need to call the `getStatement()` method, to return the correct SQL statement back to the `Select` object.
19791979

19801980
```php
19811981
<?php
@@ -1995,6 +1995,83 @@ $select
19951995
// FROM (SELECT inv_id FROM co_invoices) AS inv
19961996
```
19971997

1998+
When we need to pass parameters, we can just add them to the subselect.
1999+
2000+
```php
2001+
<?php
2002+
2003+
$invoiceId = 1;
2004+
$maxInvoice = 100;
2005+
$select
2006+
->from(
2007+
$select
2008+
->subSelect()
2009+
->columns('inv_id')
2010+
->from('co_invoices')
2011+
->where('inv_id > ', $invoiceId)
2012+
->asAlias('inv')
2013+
->getStatement()
2014+
)
2015+
->where('inv_id <', $maxInvoice)
2016+
;
2017+
2018+
// SELECT *
2019+
// FROM (SELECT inv_id FROM co_invoices WHERE inv_id > __1__) AS inv
2020+
// WHERE inv_id < __2__
2021+
```
2022+
2023+
Subselects can be used also in `JOIN` and `WHERE` conditions as follows:
2024+
2025+
```php
2026+
<?php
2027+
2028+
$select
2029+
->from('co_invoices')
2030+
->join(
2031+
'LEFT'
2032+
$select
2033+
->subSelect()
2034+
...
2035+
->asAlias('subAlias')
2036+
->getStatement()
2037+
)
2038+
;
2039+
```
2040+
2041+
For `WHERE` in particular, you do not need to convert it to a string using `getStatement()`
2042+
2043+
```php
2044+
<?php
2045+
2046+
$customerId = 1;
2047+
$total = 100.0
2048+
$select
2049+
->columns(
2050+
[
2051+
'inv_id',
2052+
'inv_total'
2053+
]
2054+
)
2055+
->from('co_invoices')
2056+
->where(
2057+
'inv_id IN '
2058+
$select
2059+
->subSelect()
2060+
->columns(
2061+
[
2062+
'cst_inv_id',
2063+
]
2064+
)
2065+
->from('co_customers')
2066+
->where('inv_total > ', $total)
2067+
)
2068+
;
2069+
2070+
// SELECT inv_id, inv_total
2071+
// FROM co_invoices
2072+
// WHERE inv_id IN (SELECT cst_inv_id FROM co_customers WHERE inv_total > __1__)
2073+
```
2074+
19982075
### Update
19992076

20002077
#### Methods

0 commit comments

Comments
 (0)