雄辩,团结一致

问题描述 投票:0回答:1

我有我的主要位置模型,这个模型hasMany联系模型。但是,联系模型需要按其类型进行分组。

我该怎么做呢?

我试图在我的位置上做一个地图,但这似乎不起作用。

$data = WebsiteLocation::query()
    ->where(['website_id' => $website['id']])
    ->orderBy('order')
    ->get()
    ->keyBy('vehicle_stock_location');

$primaryIndex = $data->map(function($location) {
    return (int)$location->primary_path === 1;
})->search(true) ?: array_keys($data->toArray())[0];

$data = $data->map(function($location) {
    $location->contact = $location->contact->groupBy('type');
    return $location;
});

这是我的位置模型:

<?php

namespace App\Models\Locations;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class WebsiteLocation extends Model
{

    protected $with = [ 'contact' ];

    public function contact(){
        return $this->hasMany(WebsiteLocationContactDetails::class)->orderBy('order', 'type');
    }

}

编辑:

我目前得到的:

[
    0 => [
        'location_name' => 'test1',
        'contact' => [
            0 => [
                'type' => 'telephone',
                'content' => '000000'
            ],
            1 => [
                'type' => 'telephone',
                'content' => '004000'
            ],
            2 => [
                'type' => 'mobile',
                'content' => '000234'
            ]
        ]
    ],
    1 => [
        'location_name' => 'test1',
        'contact' => [
            0 => [
                'type' => 'telephone',
                'content' => '000000'
            ]
        ]
    ]
]

我期待的是:

[
    0 => [
        'location_name' => 'test1',
        'contact' => [
            'telephone' => [
                0 => [
                    'type' => 'telephone',
                    'content' => '000000'
                ],
                1 => [
                    'type' => 'telephone',
                    'content' => '004000'
                ],
            ]
            'mobile' => [
                0 => [
                    'type' => 'mobile',
                    'content' => '000234'
                ]
            ]
        ]
    ],
    1 => [
        'location_name' => 'test1',
        'contact' => [
            'telephone' => [
                0 => [
                    'type' => 'telephone',
                    'content' => '000000'
                ]
            ]           
        ]
    ]
]
php laravel
1个回答
1
投票

这个怎么样 :

<?php 
$data = WebsiteLocation::where(['website_id' => $website['id']])
    ->with('contacts')
    ->orderBy('order')
    ->get();

foreach($data as $record){
  $contacts = $record->contacts->groupBy('type);
}
© www.soinside.com 2019 - 2024. All rights reserved.