多对多关系在Laravel中返回null

时间:2018-08-10 08:19:45

标签: php laravel laravel-5

我在表userclinic之间有很多关系,第三个表是user_clinics。这三个表都完美地单独返回了它们的值,但是当我调用App\User::find(1)->clinics或它的反函数时,它返回null。此外,user_clinic具有user_idclinic_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");
} 

1 个答案:

答案 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');
}