albertosetim
albertosetim

Reputation: 19

Filter a elequent relationship by date

-- Laravel 8.* --

Hi, i am trying to respond, in a api, data about football, domain.test/api/fixtures/2020-11-06 should be giving a array of leagues with fixtures for the date given.

At this point I have App\Models\League with a a filter for fixtures hasMany.

/**
 * Get all the fixtures from this league
 */
public function fixtures()
{
    return $this->hasMany('App\Models\Fixture', 'league_id', 'id');
}

And in the FixturesController I call it with a whereHas:

$leagues = League::with('fixtures')->whereHas('fixtures', function($q) use ($date) { $q->where('date', $date); })->get();


return $this->responseWithSuccess(['leagues' => $leagues ]);

But this is returning the wrong answer.

"leagues": [
        {
            "id": 4,
            "...",
            "name": "Premier League",
            "fixtures": [
                {
                    "id": 62,
                    "...",
                    "date": "2020-10-17",

Help Please! What am I doing wrong? And Can somebody tell me the best way to debug errors like that?

Upvotes: 0

Views: 747

Answers (1)

porloscerros Ψ
porloscerros Ψ

Reputation: 5088

Add the same function you have on the whereHas method to the with method.

In the way you're doing it, the whereHas is going to filter the Leagues that have a Fixture on that date, but the with is going to bring you all the Fixtures of each of those Leagues, not just those on the given date.

Another thing, for dates preferably use whereDate instead of just where.

That said, your query could look like this:

League::with(['fixtures' => function($q) use ($date) { 
        $q->whereDate('date', $date); 
    }])
    ->whereHas('fixtures', function($q) use ($date) { 
        $q->whereDate('date', $date); 
    })
    ->get();

Upvotes: 1

Related Questions