Skip to content

Commit 9cfab52

Browse files
author
rkr
committed
- Added OrderByBuilder::orderByValues
1 parent c93c645 commit 9cfab52

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/Builder/Traits/OrderByBuilder.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44
trait OrderByBuilder {
55
use AbstractDB;
66

7-
/**
8-
* @var array
9-
*/
7+
/** @var array */
108
private $orderBy = array();
119

1210
/**
@@ -32,6 +30,17 @@ public function orderBy($expression, $direction = 'asc') {
3230
return $this;
3331
}
3432

33+
/**
34+
*/
35+
public function orderByValues($fieldName, array $values) {
36+
$expr = [];
37+
foreach(array_values($values) as $idx => $value) {
38+
$expr[] = $this->db()->quoteExpression("WHEN ? THEN ?", array($value, $idx));
39+
}
40+
$this->orderBy[] = array(sprintf("CASE %s\n\t\t%s\n\tEND", $this->db()->quoteField($fieldName), join("\n\t\t", $expr)), 'ASC');
41+
return $this;
42+
}
43+
3544
/**
3645
* @param string $query
3746
* @return string

tests/Builder/SelectTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,4 +185,15 @@ public function testSubselectUnion() {
185185

186186
$this->assertEquals("(\n\tSELECT\n\t\tt1.field\n\tFROM\n\t\ttest1 t1\n\tINNER JOIN\n\t\ttest2 t2 ON t1.id=t2.id\n\tWHERE\n\t\t(t1.id > 10)\n) UNION (\n\tSELECT\n\t\tt1.field\n\tFROM\n\t\ttest1 t1\n\tINNER JOIN\n\t\ttest2 t2 ON t1.id=t2.id\n\tWHERE\n\t\t(t1.id > 10)\n)", $query);
187187
}
188+
189+
public function testOrderByValues() {
190+
$query = TestSelect::create()
191+
->field('t1.field')
192+
->from('t1', 'test1')
193+
->joinInner('t2', 'test2', 't1.id=t2.id')
194+
->orderByValues('t1.field', [5, 1, 66, 183, 99, 2, 6])
195+
->asString();
196+
197+
$this->assertEquals("SELECT\n\tt1.field\nFROM\n\ttest1 t1\nINNER JOIN\n\ttest2 t2 ON t1.id=t2.id\nORDER BY\n\tCASE `t1`.`field`\n\t\tWHEN '5' THEN '0'\n\t\tWHEN '1' THEN '1'\n\t\tWHEN '66' THEN '2'\n\t\tWHEN '183' THEN '3'\n\t\tWHEN '99' THEN '4'\n\t\tWHEN '2' THEN '5'\n\t\tWHEN '6' THEN '6'\n\tEND ASC\n", $query);
198+
}
188199
}

0 commit comments

Comments
 (0)