Select DISTINCT on a single column using Silverstripe ORM

笑着哭i 提交于 2019-12-25 08:34:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!