Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database 如何从两个组合表中获得结果_Database_Laravel_Model View Controller_Eloquent_Laravel Query Builder - Fatal编程技术网

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

Database 如何从两个组合表中获得结果,database,laravel,model-view-controller,eloquent,laravel-query-builder,Database,Laravel,Model View Controller,Eloquent,Laravel Query Builder,我有两张桌子: 匹配项: 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 如何获取exmpl的最新团队比赛记录(记录在“分数”表中): 需要获得团队id=1的最后一场比赛 有了这个,我可以得到这支球队的所有比赛,但我只需要最后一场,在分数表中有记录的地方:

我有两张桌子:

匹配项:

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
如何获取exmpl的最新团队比赛记录(记录在“分数”表中):

需要获得团队id=1的最后一场比赛

有了这个,我可以得到这支球队的所有比赛,但我只需要最后一场,在分数表中有记录的地方:

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

要从某个表中获取最新记录,您应该能够执行以下操作:

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

要获得两个表组合的结果,可以联接两个表,然后在所需的表和列上添加
orderBy
latest

比如,在你的例子中,是这样的:

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


谢谢,如果你能问我这个问题,也会很有用:如何检查分数表是否没有相关记录?因为我需要得到没有输入分数的最新比赛记录。