Now, I will show you a few tricks for querying the relationships.
has()
For example, you have a user with many projects and want to query only those with projects. For that, eloquent has a has()
method.
Before adding the has()
the code to fetch and show the result:
$users = User::with('projects')->get(); foreach ($users as $user) { print '<div><strong>' . $user->id . ': ' . $user->name . '</strong></div>'; foreach ($user->projects as $project) { print $project->title .'... '; } print '<hr />';}
And the result. As we can see, users with IDs two, five, and eight don't have projects.
Now, let's add...