问题
My table:
-----------------------------------------
| ID | RoomTypeId | ChargeTypeId | Name |
-----------------------------------------
| 1 | 23 | 32 | DD |
| 2 | 26 | 32 | DD |
| 3 | 28 | 31 | CC |
-----------------------------------------
The ORM does already DISTINCT by default, but does so on every column and returns all 3
The return I need:
-----------------------
| ChargeTypeId | Name |
-----------------------
| 32 | DD |
| 31 | CC |
-----------------------
Hoping there is actually a implemented method of achieving this without having to DB::query()
回答1:
I found that toMap()
will create a DISTINCT query based on your chosen columns
Example:
$result = \ChargeTypes::get()->toMap("ChargeTypeId", "Name")
$result->toArray():
array(2) {
[32]=>
string(2) "DD"
[6]=>
string(2) "CC"
}
UPDATE I don't believe that this actually creates a DISTINCT query it just worked in my case and the following will clearly elaborate as to why
$myArray = array();
$myArray[32] = "DD";
$myArray[32] = "DD";
$myArray[32] = "DD";
$myArray[6] = "CC";
$myArray[6] = "CC";
var_dump($myArray);
Result:
array(2) {
[32]=>
string(2) "DD"
[6]=>
string(2) "CC"
}
So in theory as long as your first key is unique, this isn't actually that bad of solution despite the redundant iterations.
来源:https://stackoverflow.com/questions/39338922/select-distinct-on-a-single-column-using-silverstripe-orm