Skip to content
Advertisement

Laravel eloquent how to get relationships relationship?

I have Users table,Jobs table and JobStatus table. I get user jobs using relationship

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

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

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:

$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:

$statuses = JobStatus::where('created_at', '>=', now())
    ->whereHas('jobs', function ($query) use ($user) {
        $query->whereUserId($user->id);
    })
    ->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement