我在表user
和clinic
之间有很多关系,第三个表是user_clinics
。这三个表都完美地单独返回了它们的值,但是当我调用App\User::find(1)->clinics
或它的反函数时,它返回null
。此外,user_clinic
具有user_id
和clinic_id
以及previlage_id
作为外键。
public function users() {
return $this->belongsToMany(User::class,'user_clinics','user_id','clinic_id');
}
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','clinic_id','user_id');
}
public function adminDashboard(Request $request) {
$clinic = new Clinic();
$User_clinic = new User_clinic();
$user = new User();
$clinic->name = $request->name;
$clinic->address = $request->address;
if($request->hasFile('logo')) {
$fileName = $request->logo->getClientOriginalName();
$request->logo->storeAs('public/logos',$fileName);
$clinic->logo = $request->logo;
}
$clinic->save();
$User_clinic->user_id = auth::user()->id;
$test=$User_clinic->clinic_id = $clinic->id;
//now hardcoded previlage_id but deal with it in future...
$User_clinic->previlage_id = 1;
$User_clinic->save();
$test= $clinic::find(2)->users;
dd($test);
//return view("admin.dashboard.dashboardFirstPage");
}
答案 0 :(得分:1)
您的关系并不平静:
public function users() {
return $this->belongsToMany(User::class,'user_clinics','user_id','clinic_id');
}
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','clinic_id','user_id');
}
应如下所示:
在用户模型中:
public function clinics() {
return $this->belongsToMany(Clinic::class,'user_clinics','user_id','clinic_id');
}
在诊所模型中:
public function users() {
return $this->belongsToMany(User::class,'user_clinics','clinic_id','user_id');
}