1 year ago

Determining if multi-level relationship records exist

Posted 1 year ago by chadhutchins

Hello, I have 3 models: Users, Movies, Shows

Users can have many Movies and Shows. Movies and Shows can only have one User.

What's the best way to determine if given a Movie record, if the related User has any Shows?

I've found a couple ways that work, but they just don't feel like the right way for some reason:

// in this flow, I already have a $movie
// you can assume $movie was passed in, but it's a App\Movie object
// the same result you'd get from something below
$movie = App\Movie::find(1);

Method 1:

if ($movie->user->shows->isEmpty()) { 
   /* no shows */ 
} else {
   /* has shows */ 

Issue here is if you do the if check on $movie->user->shows and there are no shows, it's going to throw a PHP notice that there's no "shows" member variable, so you'd first have to check if that exists.

Method 2:

// even though I already have $movie, I could do another lookup
$movie = App\Movie::has('user.shows')->where('id',$movie->id)->get();

if ($movie->isEmpty()) { 
   /* no shows */ 
} else { 
   /* has shows */ 

What's the best to do this. Thanks!

Please sign in or create an account to participate in this conversation.