其中有不存在的方法

时间:2018-03-13 22:32:19

标签: php laravel eloquent

我有2张表使用Eloquent建立了关系,我试图根据请求过滤

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

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

我有2个型号:

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';

}

我如何得到错误是通过这个:

$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();

然后我在执行查询时得到以下内容:

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

3 个答案:

答案 0 :(得分:1)

你的错误就在这里:

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

当您将->get()添加到您的雄辩查询中时,它会从数据库中获取结果,并将其作为集合返回,我认为在应用->get()

之前,您需要在没有whereHas的情况下进行尝试

答案 1 :(得分:0)

哪里失败了,因为在您第一次查询$ game之后是一个收藏而不是一个模型

应该是这样的:

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

答案 2 :(得分:0)

替换

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

使用

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