我是 laravel 的新手,我有四个表,employees、jobs、applied_jobs 和 employee_profile_picture:
员工和工作有多对多的关系
员工模型:
class Employee extends Authenticatable {
public function employeeProfilePhoto() {
return $this->hasMany('App\Models\EmployeeProfilePhoto', 'employee_id');
}
public function jobsApplied() {
return $this->belongsToMany(Job::class, 'jobs_applieds', 'employee_id', 'job_id')
->withPivot('cover_letter', 'cv_path','created_at')
->orderBy('pivot_created_at','desc');
}
}
工作模式:
class Job extends Model {
public function appliedByEmployees() {
return $this->belongsToMany(Employee::class, 'jobs_applieds', 'job_id', 'employee_id')
->withPivot('cover_letter', 'cv_path','employee_application_status');
}
}
员工资料照片模型:
class EmployeeProfilePhoto extends Model {
protected $table = 'employees_profile_photos';
public function employeePhoto() {
return $this->belongsTo(Employee::class, 'employee_id');
}
}
我想获取所有申请了 employer_id 与 jobs 表中的某个 id 匹配的工作的员工及其个人资料照片。我想用 laravel Eloquent 。如何实现这一点
最佳答案
如果你想通过特定的id过滤:
$employee = Employee::whereHas('jobsApplied', function ($query) use ($someId) {
$query->where('employee_id', $someId);
})
->with('employeePhoto')
->get();
如果您只需要已申请工作的员工:
$employee = Employee::whereHas('jobsApplied')
->with('employeePhoto')
->get();
whereHas()
它是一个 Eloquent 功能,用于检查您的案例中是否存在关系,它将仅获得已申请工作的员工,或者您可以根据特定需求(例如员工 ID)子查询条件。
关于php - Laravel 与多个外键和数据透视表的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51983965/