3

I have 3 models

Event - table('events')
Shift - table('shifts')
Workedtime - table('workedtimes')

and I can call event->shifts->workedtimes, all is fine there.

And now I want to make a query to get all Events where (Auth) user has worked.

Something like this:

Event::with('workedtimes')->where('workedtimes.uid', Auth::user()->id)->get();

But this doesn't work. What can I try next?

2 Answers 2

2

To get all events where authenticated user has worked you need to use whereHas() method:

$events = Event::whereHas('workedtimes', function($q) {
    $q->where('uid', auth()->user()->id);
})->get();
Sign up to request clarification or add additional context in comments.

1 Comment

That's the one! Thank you!
0

You may be looking for Constraing eager loading. Query:

   Event::with(['workedtimes' => function ($query) {
        $query->where('uid', Auth::user()->id );
    }])->get();

5 Comments

i copy pasted your answer and i got an error....then i copy pasted the answer from Alexey and it worked right away... :(
@lewis4u it's ok. but, it shouldnot give the error. what error you got?
I have tried again and actually it's not a functional error but instead of getting only the events where user worked i get ALL events...with your query i get 122 events and with Alexeys code i get 9
@lewis4u you got your answer, whereHas() is correct. btw this gives all the events and only the workedtimes of the authenticated user.
Ok i see. Well that was the problem. I wanted only events where user has worked. Problem solved. I hope it will help others too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.