1 year ago

Querying Relationship Existence, how to add conditions depending on an array length?

Posted 1 year ago by Quadram

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]);


This is working perfectly, but for a given 3 dimensional array...

How can I do for a given array of an n length??

->whereHas('pubTapps', function($query) use($tapps_chosen) { $query->where('tapp_id', $tapps_chosen[n-1]); })

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);

What would I have to do??? Any ideas to make it work??

Thanks a lot!

Please sign in or create an account to participate in this conversation.