如何从两个组合表中获取结果

问题描述

我有两张桌子:

匹配:

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

要得到两个表合并的结果,可以连接两个表,然后在你想要的表和列上加上orderBylatest

例如,就您而言,这将是这样的:

Match::join('scores','matches.id','=','scores.match_id')
       ->where('away_team_id','1')
       ->orWhere('home_team_id','1')
       ->latest('scores.created_at')->first()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...