I have Users table,Jobs table and JobStatus table. I get user jobs using relationship
JavaScript
x
return User::find($dto->getUserId())
->jobs()
This will return all user jobs as collection, not as relationship inside user model. Now I need to get jobs statuses, but when I try this
JavaScript
User::find($dto->getUserId())
->jobs()
->statuses()
I get error Call to undefined method
. I need to get statuses as collection so I can use where,sort by etc while getting them from db. Is there any way to do so?
I need to do something like this , but with statuses
JavaScript
return User::find($dto->getUserId())
->jobs()
->has('status')
->where('role','responsible')
->where('jobs.created_at','>=',Carbon::now()->subDays($dto->getPeriod())->toDateString())
->get();
Advertisement
Answer
To retrieve the jobs by filtering on the statuses relationship, you can do it like this:
JavaScript
$user->jobs()->whereHas('statuses', function ($query) {
// Perform filter on the query for jobs->statuses
})->get();
For more information about querying relationship existence: https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence
If you want to retrieve the statuses instances, you can do it like this:
JavaScript
$statuses = JobStatus::where('created_at', '>=', now())
->whereHas('jobs', function ($query) use ($user) {
$query->whereUserId($user->id);
})
->get();