Reputation: 321
I am quite new to laravel, I have four tables, employees, jobs, applied_jobs, and employee_profile_picture:
Employee and Jobs has many to many relationships
Employee Model:
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');
}
}
Jobs Model:
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');
}
}
Employee Profile Photo Model:
class EmployeeProfilePhoto extends Model {
protected $table = 'employees_profile_photos';
public function employeePhoto() {
return $this->belongsTo(Employee::class, 'employee_id');
}
}
I want to get all the employees and their profile picture who have applied for the job where employer_id matches to some id in jobs table. I want to use laravel eloquent. How can this be achieved
Upvotes: 1
Views: 3394
Reputation: 146191
You may try something like the following to get all employees with their profile photos where an employee has been applied for a job and matches the employer_id
in jobs
table:
$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();
Upvotes: 0
Reputation: 7420
If you want to filter by specific id:
$employee = Employee::whereHas('jobsApplied', function ($query) use ($someId) {
$query->where('employee_id', $someId);
})
->with('employeePhoto')
->get();
If you want only employees that have applied for a job:
$employee = Employee::whereHas('jobsApplied')
->with('employeePhoto')
->get();
whereHas()
its an eloquent function that checks the relationship existence in your case it will get only employees that have applied for a job, or you can subquery the condition based on a specific need for instance employeee id.
Upvotes: 1
Reputation: 260
I suggest the following answer
Employee::with(['employeeProfilePhoto', 'jobsApplied'])->get();
I don't know what your problem.
Upvotes: 0