Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0

Nope, not a bug. The closure only works on the eager loaded resource. Look at the has() and whereHas() methods to achieve what you want. It's on the same docs page: http://laravel.com/docs/eloquent#querying-relations

$users = User::whereHas('posts', function($q)
{
    $q->where('title', 'like', '%first%');

})->get();
Last updated 2 years ago.
0

@shabushabu not entirely true:

@l4zl0w To get what you wanted, do as shabu said. But still you can use the same construct to limit loaded posts:

$users = User::whereHas('posts', function($q)
{
  $q->where('title', 'like', '%first%');
})->with('posts')
->get();
// loads only users that have related posts matching given title but with all related posts


$users = User::with( ['posts' => function($q)
{
  $q->where('title', 'like', '%first%');
] })->get();
// loads only all the users and ONLY related posts matching given title


$users = User::with( ['posts' => function($q)
{
  $q->where('title', 'like', '%first%');
]})
->whereHas('posts', function($q)
{
  $q->where('title', 'like', '%first%');
})->get();
// a combination of the two: only users that have the matching posts, and only those  posts

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

l4zl0w l4zl0w Joined 12 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.