【问题标题】:Laravel Relationships with multiple foreign key and pivot table具有多个外键和数据透视表的 Laravel 关系
【发布时间】: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


【解决方案1】:

我建议以下答案

Employee::with(['employeeProfilePhoto', 'jobsApplied'])->get();

我不知道你的问题。

【讨论】:

  • jobs表有哪些列?
【解决方案2】:

您可以尝试以下方法来获取所有员工的个人资料照片,其中员工已申请工作并与jobs 表中的employer_id 匹配:

$employer_id = 'get the employer_id...';

$result = Employee::whereHas('jobsApplied', function($query) use ($employer_id) {
    $query->where('employer_id', $employer_id);
})->with('employeeProfilePhoto', 'jobsApplied')->get();

【讨论】:

  • 我得到员工和个人资料照片我如何获得工作详细信息和数据透视表详细信息
  • 你也应该得到jobsApplied 的deails,注意with('jobsApplied')。
【解决方案3】:

如果要按特定id过滤:

$employee = Employee::whereHas('jobsApplied', function ($query) use ($someId) {
    $query->where('employee_id', $someId);
})
->with('employeePhoto')
->get();

如果您只想要已申请工作的员工:

$employee = Employee::whereHas('jobsApplied')
    ->with('employeePhoto')
    ->get();

【讨论】:

  • 为什么在调用 get 之前调用 load?通常你会在调用 get 之前使用with。 load 是您在获取模型后使用的内容。
  • @Tschallacka 很好,刚刚切换到with instead 谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
相关资源
最近更新 更多