Curtis
Curtis

Reputation: 2704

Method whereHas does not exist

I've got 2 tables which have relationships using Eloquent of which I'm attempting to filter based on requests.

+----------+---------+
| Table 1            |
+----------+---------+
| id       | rl_id   |
+----------+---------+
| 39       | 2       |
| 40       | 234     |
| 41       | 345     |
+----------+---------+

+----------+---------+
| Table 2 - rl       |
+----------+---------+
| id       | type    |
+----------+---------+
| 2        | Hel..   |
| 234      | Umb...  |
| 345      | Pot.    |
+----------+---------+

I've got 2 Models:

Class Listing extends Model {

    protected $table = 'listings';

    public function rocketleague()
    {
        return $this->belongsToMany('App\Models\RocketLeague');
    }

}

Class Game extends Model {

    protected $table = 'games';

    public function listings()
    {
        return $this->hasMany('App\Models\Listing');
    }

}

Class RocketLeague extends Model {

    protected $table = 'rl_items';

}

How I'm getting the error is via this:

$game = Game::find($game_id);
$game->listings = Listing::where('game_id', $game_id)->get();

//I perform a filter here based on request
$type = "Hel...";
$game->listings->whereHas('rocketleague', function($q) use($type) {
    $q->where('type', $type);
})->get();

And then I'm being given the following upon the query being performed:

(1/1)BadMethodCallException
Method whereHas does not exist.

Upvotes: 2

Views: 13540

Answers (3)

leandro ramos
leandro ramos

Reputation: 1

Replace

$game->listings->whereHas('rocketleague', function($q) use($type) {
    $q->where('type', $type);
})->get();

with

$game->listings->newQuery()->whereHas('rocketleague', function($q) use($type) {
    $q->where('type', $type);
});

Upvotes: 0

Anibal Itriago
Anibal Itriago

Reputation: 1051

wherehas fails because after your first query $game is a collection and not a model

Should be something like:

$filteredListing = 
Listing::where('game_id', $game_id)->whereHas('rocketleague', function($q) use($type) {
    $q->where('type', $type);
})->get();

Upvotes: 0

bestestefan
bestestefan

Reputation: 871

your mistake is here:

$game->listings = Listing::where('game_id', $game_id)->get();

when you add ->get() to your eloquent query it gets results from database, and returns them as collection, I think you need to try without ->get() before applying whereHas

Upvotes: 2

Related Questions