首页 > 解决方案 > 在一个模型中调用 2 个连接函数

问题描述

我想知道如何从我的 Match 模型中链接两个范围,这是两个范围:

public function scopeMainMatches($query){
    return $query->where('matches.type','main');
}

public function scopeDotaMatches($query,$type){
    return $query
            ->join('leagues','leagues.id','=','matches.id')
            ->select('matches.*')
            ->where('leagues.type',$type);
}

这是我的控制器,它返回桌面联赛的 ID 联赛:

public function showDotaMatches($ptr){   
    $_matches = \App\Match::mainMatches()
                            ->whereNotIn('status',['ongoing','open'])
                            ->get()
                            ->load('league','teamA', 'teamB')
                            ->where('league_id','1')
                            ->sortByDesc('schedule')
                            ->slice($ptr, 10);

我想要发生的是:

public function showDotaMatches($ptr,$request){
    $_matches = \App\Match::mainMatches()
                            ->dotaMatches($request-type)
                            ->where('leagues.type','dota2') // instead of ('league_id','1')

使代码干净。但是当我链接这两个范围时,它说 SQL 约束违规,因为匹配表和联赛表都有状态和类型。谁能帮我解决这个问题?

标签: laravellaravel-5

解决方案


我想你在whereHas查询:

// Retrieve all matches with at least one league with the type 'dota2'
$matches = App\Match::whereHas('leagues', function ($query) {
    $query->where('type', 'dota2');
})->get();

那么你就不需要你的加入了scopeDotaMatches


推荐阅读