Constraining Eager Loads Returning Unfiltered

1

I have a problem with eager loading in Laravel 5.4.24. Following the documentation, I added the code:

$profiles = Profile::with(['platforms' => function ($query) {
                $query->where('name', 'PC');
            }])->get();

The expected return was a Collection with only Profiles that have Platform name = PC . Instead I received all the records from my bank, where the correct would be to receive 37 records. As shown in the query below:

SELECT COUNT(*) FROM db.profiles PROF
INNER JOIN db.platform_profile PLATPROF ON (PROF.id = PLATPROF.profile_id)
INNER JOIN db.platforms PLAT ON (PLATPROF.platform_id = PLAT.id)
WHERE PLAT.name = 'PC';

What am I letting go? Could someone help me with this?

Model Profile:

class Profile extends Model
{
    public function platforms()
    {
        return $this->belongsToMany('App\Models\Platform')->withTimestamps();
    }
}

Model Platform:

class Platform extends Model
{
  public function profiles()
  {
    return $this->belongsToMany('App\Models\Profile')->withTimestamps();
  }
}
    
asked by anonymous 01.06.2017 / 00:04

1 answer

0

Instead of with , put whereHas , so you can filter the data using the relation and bring all Profile through the filter:

$profiles = Profile::whereHas('plataforms', function($query)
           {
               $query->where('name','PAC'); 
           })
           ->get();

Remember that nothing prevents the use of the two commands that also brought the result through the filters, however your question is required to use whereHas :

$profiles = Profile::with(['platforms' => function ($query) 
           {
               $query->where('name', 'PC');
           }])
           ->whereHas('plataforms', function($query)
           {
               $query->where('name','PAC'); 
           })
           ->get();

01.06.2017 / 03:41