我有我的主要位置模型,即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'
]
]
]
]
]
答案 0 :(得分:1)
如何?
<?php
$data = WebsiteLocation::where(['website_id' => $website['id']])
->with('contacts')
->orderBy('order')
->get();
foreach($data as $record){
$contacts = $record->contacts->groupBy('type);
}