Самое элегантное решение, которое смог из себя выдавить
Буду рад правкам.
$linkeds = [];
$lookups = (new Lookup)
->query()
->select([
'lookup_id',
'record_id',
'lookup_list_id',
'linked_record_id',
'data',
'element_label',
'field_name',
'sequence_order',
'field_no',
'archive'
])
->where('company_id', UserData::getDataUser()->company_id)
->where('lookup_list_id', $lookup_list_id)
->orderBy('sequence_order')
->get()
->groupBy(function($item, $key) use (&$linkeds) {
if($item->linked_record_id > 0)
{
$linkeds[$item->record_id] = $item->linked_record_id;
}
return $item->record_id;
});
$records = [];
foreach ($lookups as $record_id => $node)
{
$records[$record_id]['data'] = $node;
if(isset($linkeds[$record_id]))
{
$link = (new Lookup)
->query()
->select([
'lookup_id',
'record_id',
'lookup_list_id',
'linked_record_id',
'data',
'element_label',
'field_name',
'sequence_order',
'field_no',
'archive'
])
->where('company_id', UserData::getDataUser()->company_id)
->where('record_id', $linkeds[$record_id])
->orderBy('sequence_order')
->get()->toArray();
$records[$record_id]['link_data'] = $link;
}
}