Home > Net >  Get model only if relationship has data
Get model only if relationship has data

Time:02-03

I am working on a Laravel project and I have these two models User and Post:

user
-id
-name
-status

post
-id
-id_user
-name

What should I change from next line to have only User with at least one Post (I already created the one-to-many relationship in the models)?

$users = User::where('status', true)->get();

CodePudding user response:

If there is a one-to-many relationship, you can use https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence and do this:

User::has('posts')->whereTrue('status')->get()

If you need more power over has, you could use whereHas.

  •  Tags:  
  • Related