雄辩的分组依据,但仅分组第一行

时间:2019-02-14 17:10:54

标签: php eloquent

我需要根据类型对以下行进行分组,但是我需要Collection仅具有该项目,而不是其中包含1个项目的数组。

示例数据库行:

id     location_id      type      section_id       content
0          2          telephone        1          123135145
1          2           mobile          1          245446546

预期结果:

[
    'telephone' => [
        'id' => 0,
        'location_id' => 2,
        'type' => 'telephone',
        'section_id' => 1,
        'content' => 123135145
    ],
    'mobile' => [
        'id' => 1,
        'location_id' => 2,
        'type' => 'mobile',
        'section_id' => 1,
        'content' => 245446546
    ]
]

实际结果:

[
    'telephone' => [
        0 => [
            'id' => 0,
            'location_id' => 2,
            'type' => 'telephone',
            'section_id' => 1,
            'content' => 123135145
        ]
    ],
    'mobile' => [
        0 => [
            'id' => 1,
            'location_id' => 2,
            'type' => 'mobile',
            'section_id' => 1,
            'content' => 245446546
        ]
    ]
]

这是我的口才

$contactDetails = $this->contactDetails()->where([ 'section_id' => 1 ])->get()->groupBy('type');

contactDetails()方法是关系:

public function contactDetails(){

    return $this->hasMany(WebsiteLocationContactDetails::class);

}

1 个答案:

答案 0 :(得分:1)

我不是一个有说服力的专家,但我认为这个结果是正确的,您应该在得到结果之后简单地调整结果。

尝试使用this fiddle

<?php
$array = [
    'telephone' => [
        0 => [
            'id' => 0,
            'location_id' => 2,
            'type' => 'telephone',
            'section_id' => 1,
            'content' => 123135145
        ]
    ],
    'mobile' => [
        0 => [
            'id' => 1,
            'location_id' => 2,
            'type' => 'mobile',
            'section_id' => 1,
            'content' => 245446546
        ]
    ]
];

foreach($array as $k => $v) {
    $newArray[$k] = $v[0];
}

echo '<pre>'; print_r($newArray); echo '</pre>';
?>