2 回答

TA貢獻1843條經驗 獲得超7個贊
如果您沒有belongsToMany在Instructor模型中建立關系,DriverLicenseType我建議您將其放入:
public function licenseTypes()
{
return $this->belongsToMany(DriverLicenseType::class, 'instructors_license_types', 'instructor_id', 'driver_license_type_id');
}
$user = User::find(1);
$licenseTypes = $user->instructor->licenseTypes->pluck('type')->unique();
或者,如果您需要$licenseTypes采用問題中的格式,您可以執行以下操作:
$licenseTypes = $user->instructor->licenseTypes->map(function ($item) {
return [$item->id, $item->type];
});

TA貢獻1982條經驗 獲得超2個贊
通過添加以下函數,您可以直接從 Instructors 模型中獲取 driver_license_types:
//PathToModel\Instructor.php
public function license_types()
{
return $this->belongsToMany('PathToModel\LicenseTypes', 'instructors_license_types');
}
還將其添加到 LicenseType 模型中:
//PathToModel\LicenseTypes.php
public function instructors()
{
return $this->belongsToMany('PathToModel\Instructors', 'instructors_license_types');
}
通過這種方式,您將能夠刪除代碼中的 foreach 語句之一:
$user = User::find($id);
if($user->instructor){
$tmp = [];
foreach ($user->instructor->license_types as $data) {
array_push($tmp, [$data->id, $data->type]);
}
$user->types = $tmp;
}
這只是跳過數據透視表(instructos_license_types),有關這方面的更多信息,您可以在此處查看文檔。
- 2 回答
- 0 關注
- 173 瀏覽
添加回答
舉報