laravel - 在一个模型中调用 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 约束违规,因为匹配表和联赛表都有状态和类型。谁能帮我解决这个问题?
解决方案
我想你在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
。
推荐阅读
- python - darkflow - AttributeError:“NoneType”对象没有属性“find”
- c# - 同时启动多个线程而不会减慢
- cdn - 从 CDN 缓存中删除文件
- python - 如何从另一个线程更新 GUI?使用蟒蛇
- python - 为什么 Python 中的 traceback.extract_stack() 这么慢?
- php - 对数据库中的记录执行更改的按钮(HTML TABLE)
- ruby - 带多行缩进的字符串插值
- javascript - chrome 通知不显示并返回错误
- angular - Angular 5 - 将数据存储在服务而不是组件中?
- iis-express - 从同一 LAN 上的另一台计算机调用本地 API (IIS Express)