13

I have two Models User and Owner with many to many relationship

I want to fetch only those users who don't have owner

how can I get using eloquent

i tried

$query = User::whereHas('userOwners', function ( $subquery ){
                $subquery->whereNull('owner_id');                            
            })->get();

but not working.

1
  • @onlineThomas This is project management website where user(type1) assign project to user(type2) for followup.each user(type2) must have project, so need to find user who don't have any project. (Project is nothing its information of actual project owner(owners contact info for followup), ) Commented Sep 14, 2020 at 18:29

3 Answers 3

41

Eloquent has a way to query an absent relationships, it should work like this in your case:

$query = User::doesntHave('userOwners')->get();
Sign up to request clarification or add additional context in comments.

1 Comment

Its Worked. Thank you very much!
0
 User::with('userOwners')
        ->whereHas('userOwners', function ($query) {
            $query->wherehas('owner_id');
        })
        ->where('user_status', 1)->get();

use second where if you want to filter on user

use first where if you want to filter on Owner

Comments

-4

I think you should just change your query like:

$query = User::whereHas('userOwners')->get();

Hope this work for you!!!

3 Comments

He's asking for the opposite, users that do not have owners
This returning users with owner but I want without owners
@SharadKale Ok let me check

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.