Skip to content

Commit d38694d

Browse files
committed
added casting value
1 parent 22869d8 commit d38694d

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ I often use this in my work and I hope it will be useful to you!
1414

1515
## Last added
1616

17+
2020/12/10 - Added casting for withSum('items:price:signed') and others
1718
2020/11/03 - Added method [withMath](https://github.com/Alexmg86/laravel-sub-query#working-with-columns)
1819
2020/10/21 - Added [some sugar](https://github.com/Alexmg86/laravel-sub-query#sugar)
1920
2020/10/06 - Added caching of [received data](https://github.com/Alexmg86/laravel-sub-query#caching)
@@ -53,6 +54,10 @@ echo $invoices[0]->items_price_min;
5354
echo $invoices[0]->items_price_max;
5455
echo $invoices[0]->items_price_avg;
5556
```
57+
The resulting value can be loaded through the third parameter. Some types for example: date, datetime, time, char, signed, unsigned, binary.
58+
```php
59+
$invoices = Invoice::withSum('items:price:signed')->get();
60+
```
5661
### The following methods apply to all methods!!!
5762

5863
You may add the sum for multiple relations as well as add constraints to the queries:

src/LaravelSubQuery.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ protected function withSubQuery($relations, $type, $orderType = null)
112112
// as a sub-select. First, we'll get the "has" query and use that to get the relation
113113
// sum query. We will normalize the relation name then append _{column}_sum as the name.
114114
foreach ($columns as $column) {
115+
$queryRow = '' . $type . '(' . $column . ')';
116+
if (isset($nameExplode[2])) {
117+
$queryRow = 'CAST(' . $type . '(' . $column . ') as ' . $nameExplode[2] . ')';
118+
}
119+
115120
$query = $relation->getRelationExistenceQuery(
116121
$relation->getRelated()->newQuery(),
117122
$this,

tests/LaravelSubQueryWithSumTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,19 @@ public function testSortingScopes()
131131
$query .= ' from "invoices"';
132132
$this->assertSame($query, $result);
133133
}
134+
135+
public function testCastColumn()
136+
{
137+
$invoice = Invoice::create(['id' => 1, 'name' => 'text_name']);
138+
for ($i = 1; $i < 11; $i++) {
139+
Item::create(['invoice_id' => $invoice->id, 'price' => $i, 'price2' => $i + 1]);
140+
}
141+
142+
$results = Invoice::withSum('items:price,price2:signed');
143+
144+
$this->assertEquals(
145+
['id' => 1, 'name' => 'text_name', 'items_price_sum' => 55, 'items_price2_sum' => 65],
146+
$results->first()->toArray()
147+
);
148+
}
134149
}

0 commit comments

Comments
 (0)