Hello,
I'm working on a filtering system, where I need to find users which have certain properties depending on relations.
To be more specific, a user
has one user_profile
which belongs to a year_group
.
Depending on the input, a user should be filtered on the fields user_profile.region
and user_profile.year_group_id
. This resulted in the following try:
<?php
$query = Model\User::where('type', '=', $member)
->with('profile.yearGroup')
->orderBy('lastname');
$with = array();
if(Input::has('region')) {
// (...)
$with['profile'] = function($q) use ($region) {
$q->where('region', '=', $region);
}
}
if(Input::has('yeargroup')) {
// (...)
$with['profile'] = function($q) use ($yeargroup) {
$q->where('year_group_id', '=', $yeargroup);
}
}
$query ->with($with);
$memberlist = $query ->paginate(10);
?>
However, (1) one problem is that $with['profile']
is (obviously) overwritten and (2) this still selects all users, while I want to select only those which satisfy all where conditions and (3) I want to use the year_group
-data as well.
So, in summary, what I actually would like to do is to select those members which have user.type=?
, user_profiles.region=?
and user_profiles.year_group_id=?
and eager load the year groups.
How should I tackle these problems?
Input
, then apply where()
in a loop for whereHas()
whereHas()
, like in linked post, using data from 1with('profile.yearGroup')
, but this will load all the related models, not filtered. So should you need only filtered, use the constraints on this too.Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community