问题
I would like to filter an item (pubs, in this case) by some characteristics that are stored in a separate table (tapps, in this case), and both are related by pub_tapps.
I have the following tables: pubs, tapps, pub_tapps(pub_id, tapp_id)
The relation between Pub and Tapp is the following:
public function pubTapps()
{
return $this->belongsToMany(Tapp::class, 'pub_tapps');
}
in my Pub model I tried the following testing for an array $request=[5,8, 7]:
public function pubsFilteredByTapps(FilteredTappsPubsRequest $request)
{
$tapps_chosen = $request->get('tapps');
$tapps_chosen = is_string($tapps_chosen) ? explode(',', str_replace('"', '', $tapps_chosen)) : $tapps_chosen;
return Pub::whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->where('tapp_id', $tapps_chosen[0]);
})
->whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->where('tapp_id', $tapps_chosen[1]);
})
->whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->where('tapp_id', $tapps_chosen[2]);
})
->get();
}
This is working perfectly, but for a given 3 dimensional array...
How can I do for an array of an n length??
I tried this, but doesn't work at all (returns an empty array):
return $pubs = Pub::whereHas('pubTapps', function ($query) use
($tapps_chosen) {
foreach ($tapps_chosen as $tappId) {
$query->where('tapp_id', $tappId);
}
})->get();
What would I have to do??? Any ideas to make it work??
Thanks a lot!
回答1:
Use this:
$query = Pub::query();
foreach ($tapps_chosen as $tappId) {
$query->whereHas('pubTapps', function($query) use($tappId) {
$query->where('tapp_id', $tappId);
});
}
return $query->get();
回答2:
How about this?
public function pubsFilteredByTapps(FilteredTappsPubsRequest $request)
{
$tapps_chosen = $request->get('tapps');
$tapps_chosen = is_string($tapps_chosen) ? explode(',', str_replace('"', '', $tapps_chosen)) : $tapps_chosen;
return Pub::whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->whereIn('tapp_id', explode(',' $tapps_chosen));
})->get();
}
This way if you have any number of IDs in the array, eloquent will generate a request with IN clause and you will get a proper result.
来源:https://stackoverflow.com/questions/50333566/querying-relationship-existence-how-to-add-conditions-depending-on-an-array-len