问题描述
我有两张桌子:
匹配:
id round league_id home_team_id away_team_id match_date
分数:
id match_id home_team_score away_team_score created_at updated_at
如何获取最近的球队比赛,在'scores'表中有记录,例如:
需要获取 team_id = 1 的最后一场比赛
有了这个,我得到了这支球队的所有比赛,但我只需要最后一场,以及得分表中的记录:
$lastMatch = Match::where('away_team_id','=','1')
->orWhere('home_team_id','1')
->get();
解决方法
要从某个表中获取最新记录,您应该可以执行以下操作:
Model::latest()->first();
或
Model::latest('created_at','desc'))->first();
或
Model::orderBy('created_at')->first();
要得到两个表合并的结果,可以连接两个表,然后在你想要的表和列上加上orderBy
或latest
。
例如,就您而言,这将是这样的:
Match::join('scores','matches.id','=','scores.match_id')
->where('away_team_id','1')
->orWhere('home_team_id','1')
->latest('scores.created_at')->first()