Is it possibly to make a WHERE query on a eager loaded relationship?
Say my users table has a name, and I'd like to filter profiles by the name of the user
-id
-name
With a join:
$query = Profile::leftJoin('users', 'users.id', '=', 'profiles.user_id')
->with('rank', 'game', 'roles', 'gamemodes', 'characters')
->where(function($query)
{
if(\Request::get('name'))
$query->where('name', 'LIKE', '%' . \Request::get('name') . '%');
})
->get();
Into something like:
$query = Profile::with('user', 'rank', 'game', 'roles', 'gamemodes', 'characters')
->where(function($query)
{
if(\Request::get('name'))
$query->where('user.name', 'LIKE', '%' . \Request::get('name') . '%');
})
->get();
Just wanted to know if this is possible, whether it's better or not, I don't know. It would make it easier as a lot of tables I want to join have the same column names, and I'd have to make a lot of aliases.
Cheers
Actually, I think I solved it. I was looking in the wrong part of the documentation.
This seems to work:
$query = Profile::with('user', 'rank', 'game', 'roles', 'gamemodes', 'characters')
->whereHas('user', function($query)
{
if(\Request::get('name'))
$query->where('name', 'LIKE', '%' . \Request::get('name') . '%');
})
->get();
Will come back, if this isn't the case after all.
Bonus Update:
I just realized that if I getXAttribute() I can then append this on my object and don't have to use ->with(). Which allows me to use the built in pagination
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community