0

How can I retrieve all records of my model based on certain ID's in my pivot table?

I have the following 3 tables

users; id, name

stats; id, name

stats_selected; user_id, stats_id

Model

User.php

public function stats()
{
            return $this->belongsToMany('App\stats', 'stats_selected', 'user_id', 'stats_id')->withTimestamps();
}

Controller

        // Get all users with example of stats ID's
        $aFilterWithStatsIDs = [1,10,13];

        $oUser = User::with(['stats' => function ($query) use($aFilterWithStatsIDs ) {
                    $query->whereIn('stats_id', $aFilterWithStatsIDs);
                }])
                ->orderBy('name', 'desc')
                ->get()

This outputs just all the users. Btw, fetching users with there stats and saving those selected stats into the DB is not a problem. That works fine with the above lines.

But how do I retrieve only the users which has certain stats_id's within them?

Flyhnl
  • 5
  • 1

1 Answers1

1

But how do I retrieve only the users which has certain stats_id's within them?

Use a whereHas conditional.

User::whereHas('stats', function ($stats) use ($aFilterWithStatsIDs) {
    $stats->whereIn('id', $aFilterWithStatsIDs);
});
Shane
  • 1,190
  • 15
  • 28