Constraining Eager Loads returning unfiltered

Asked

Viewed 28 times

1

I have a problem with Eager loading on 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 only with Profiles who have Platform = PC. Instead I received all the records from my database, 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';

Retorno do Workbench da query rodada

What am I missing? 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();
  }
}

1 answer

0


In place of with, place whereHas, so that it can filter the data through the relationship and bring all the Profile by 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, but by your question is mandatory the use of the whereHas:

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

References

  • 1

    It worked as expected. Thanks for the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.