【发布时间】:2019-01-29 17:23:49
【问题描述】:
我是 laravel 的新手,我有四个表,employees、jobs、apply_jobs 和employee_profile_picture:
Employee 和 Jobs 有多对多的关系
员工模型:
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');
}
}
我想获取所有已申请工作的员工及其个人资料图片,其中雇主 ID 与工作表中的某个 ID 匹配。我想用 laravel 雄辩。如何实现这一点
【问题讨论】:
-
在哪里,在控制器中?你试过什么?在模范员工中?
-
@Erubiel $candidates = Job::with('appliedByEmployees.employeeProfilePhoto') ->where('jobs.employer_id',$currentEmployer->id) ->get();我在控制器中试过这个
-
你想在单个查询中使用它吗,如果你要迭代候选人,如 foreach($candidate on $candidates) 你可以访问像employeeProfilePhoto这样的候选人关系
-
另外,您的employeeProfilePhoto 被定义为hasMany 关系...这将带来更多的一组行,而不是给定的行,从而使其模棱两可。
-
单个查询会更好,因为我还需要从员工和其他与员工(如同一查询中的员工电话)有关系的表中获取其他数据
标签: php mysql database laravel eloquent