早上好,我有一个laravel 5.8项目,但我遇到了一些问题 我有这个代码
public function doctor_details($doctor_id){
$doctor = DB::table('doctors')->select('specification')->where('doctor_id', $doctor_id)->get>first();
$specs_data = explode(',', $doctor_specs);
$specs_array = [];
foreach ($specs_data as $doctor_spec) {
$doctor_spec_result = DB::table('specializations')->where { return explode('speciality_id'',', $doctor_spec)->get();
foreach ($doctor_spec_result as $doctor_spec_res) {
$specs_array[] = $doctor_spec_res->speciality_name;
}
}
return view ('doctor_details', compact('doctor', 'specs_array'));
}
现在我是否做dd($ doctor_spec_result);结果是
如您所见,我得到一个空数组,但是如果我做dd($ specs_data);结果是
如您所见,肯定有数据,但我无法使其工作
这是我的刀刃
<div class="row">
<div class="col-lg-12">
<h3>{{ $doctor->doctor_name }}</h3>
</div>
<div class="col-lg-12">
@foreach( $specs_array as $spec_output )
<p>{!! $spec_output !!}</p>
@endforeach
</div>
</div>
答案 0 :(得分:1)
我认为您正在尝试获取仅包含所查询的特定行的specification
字段值的列表,以便随后可以获取specialty_name
。您可以在构建器上使用pluck
方法来为您执行此操作。如果doctor_id
进行的搜索可以返回多个结果:
$doctor_specs = DB::table('doctors')
->where('doctor_id', $doctor_id)
->pluck('specification')
->transform(function ($item) { return explode(',', $item); })
->flatten();
$specs_array = DB::table('specializations')
// use whereIn to find all the rows by 'specialty_id'
->whereIn('speciality_id', $doctor_specs)
->pluck('specialty_name')
->toArray();
return view ('doctor_details', compact('doctor', 'specs_array'));
Laravel 6.x Docs - Database - Query Builder - Retrieving Results pluck
Laravel 6.x Docs - Collections - Methods - transform
Laravel 6.x Docs - Collections - Methods - flatten
更新:
尽管doctor_id
是一个密钥,但是只有一个,因此我们可以删除收集方法并简化处理:
$doctor_specs = explode(
',',
DB::table('doctors')->where('doctor_id', $doctor_id)
->value('specification')
);
理想:
或者如果$doctor
是从doctors
表的所有列中检索到的,包括specification
:
$doctor_specs = explode(',', $doctor->specification);
答案 1 :(得分:0)
您可以使用join简化代码
$doctor_spec_result = DB::table('doctors')
->select('specializations.speciality_name')
->join('specializations','specializations.speciality_id','doctors.specification')
->where('doctors.doctor_id', $doctor_id)
->get();
return view ('doctor_details', compact('doctor', 'doctor_spec_result '));
答案 2 :(得分:0)
更改此行。
$doctor_spec_result = DB::table('specializations')->where('speciality_id', $doctor_spec)->get();
您正在检查Wearg属性。当您在0索引中获得规格时。
speciality_id to specification