我有两个表医生和专业和一个数据透视表doctor_specialities。
在Doctor模型中,我定义了这样的关系 -
public function specializations(){
return $this->belongsToMany('App\Specialization', 'doctor_specialities', 'speciality_id', 'doctor_id');
}
在专业化模型中,关系就像这样 -
public function doctors(){
return $this->belongsToMany('App\Doctor', 'doctor_specialities', 'speciality_id', 'doctor_id');
}
我正在接受像这样专业化的所有医生 -
$doctors = Specialization::find($request->specialization)->doctors
->where('city_id', $request->city);
工作正常。我得到了正确的输出。
但是现在我想打印每个医生的所有专业,但它返回一个空数组。
foreach ($doctors as $doctor) {
var_dump($doctor->specializations);
}
我得到的输出是 -
object(Illuminate\Database\Eloquent\Collection)[218]
protected 'items' =>
array (size=0)
empty
如何打印每位医生的专业?
答案 0 :(得分:0)
$specialization = Specialization::find($request->specialization)->doctors
->where('city_id', $request->city);
我猜你不清楚你想要达到的目标?
如果您想要特定专业的医生,您应该这样做;
$specialization = Specialization::with(['doctors' => function ($query) {
$query->where('city_id', $request->city);
}])->find( $request->specialization);
并循环通过医生
foreach($specialization->doctors as $doctor){
do what ever you want
}
答案 1 :(得分:0)
对于您更新的问题,在定义Doctor模型上的特化关系时,第三个参数是您定义关系的模型的外键名称(在您的情况下是Doctor),而第四个参数是外来的您要加入的模型的密钥名称(专业化)。关系应定义如下:
public function specializations(){
return $this->belongsToMany('App\Specialization', 'doctor_specialities', 'doctor_id', 'speciality_id');
}