我正在尝试以下操作:
我使用以下功能获取与患者相关的所有临床检验:
print('character moving left')
第一组代码:
public function getPatientsClinicTests(Specialist $id)
{
$patientClinicTests = $id->patients()
->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
->get()
->pluck('PatientClinicTests')
->filter(function ($value) { return !empty($value); });
$result = [];
foreach ($patientClinicTests as $array) {
$result = array_merge($result, $array->toArray());
}
return $result;
}
为我带来了如下的数组集合:
$patientClinicTests = $id->patients()
->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
->get()
->pluck('PatientClinicTests')
->filter(function ($value) { return !empty($value); });
由于我需要返回一个元素数组,因此将得到的数组组合如下:
[
[
{
"id": 16,
"patient_id": 7,
"medical_condition_id": null,
"patient": {
"id": 7,
"user_id": 7,
"pigment_id": 14,
"id_medical_history": "6219116421",
"user": {
"id": 7,
"name": "Austen Wiegand",
}
}
},
.....
],
[
{
"id": 22,
"patient_id": 1,
"medical_condition_id": null,
"patient": {
"id": 7,
"user_id": 1,
"pigment_id": 14,
"id_medical_history": "6219116421",
"user": {
"id": 7,
"name": "Gregor Wiegand",
}
}
},
.......
]
]
这将返回一个数组,如下所示:
$result = [];
foreach ($patientClinicTests as $array) {
$result = array_merge($result, $array->toArray());
}
return $result;
我想知道是否有一个更明智的选择,使用Eloquent而不是foreach语句作为元素数组返回。
非常感谢您的帮助!
答案 0 :(得分:0)
您可以使用all()方法将您的集合转换为数组:
$patientClinicTests = $id->patients()
->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
->get()
->pluck('PatientClinicTests')
->filter(function ($value) { return !empty($value); })->all();
请注意,如果要遍历数组,则应在过滤后重建数组索引……您可以使用“值”方法做到这一点:
$patientClinicTests = $id->patients()
->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
->get()
->pluck('PatientClinicTests')
->filter(function ($value) { return !empty($value); })->values()->all();
更多详细信息:
答案 1 :(得分:0)
也许您可以在数组上使用collect方法将其分配到单个数组中
https://laravel.com/docs/7.x/collections
该链接可能会有所帮助
$collection = collect($patientClinicTests);
$collections = $collection->values()->all();
也许这会起作用
答案 2 :(得分:0)
Flatten方法可以帮助我在不使用foreach语句的情况下提供单个数组array_merge()函数:
$patientClinicTests = $id->patients()
->with('PatientClinicTests', 'PatientClinicTests.Patient.User')
->get()
->pluck('PatientClinicTests')
->filter(function ($value) { return !empty($value); })->flatten()->all();
我将按照建议使用表连接进行测试