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

How to get result from two combined tables

我有两个 table:

匹配项:

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

如何获取在table'scores'中有记录的最新球队比赛,例如:

需要获得最后一场比赛 team_id = 1

有了这个我就得到了这支球队的所有比赛,但我只需要最后一场,并且有得分记录的地方table:

$lastMatch = Match::where('away_team_id', '=', '1')
        ->orWhere('home_team_id', '=', '1')
        ->get();

要从某些 table 获取最新记录,您应该可以这样做:

Model::latest()->first();

Model::latest('created_at', 'desc'))->first();

Model::orderBy('created_at')->first();

要得到两个table合并的结果,可以将两个table合并,然后在[=26=上加上orderBylatest ] 和你想要的专栏。

例如,在您的情况下,应该是这样的:

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