Laravel Eloquent在足球比赛日程中的多重关系

时间:2017-12-13 15:32:29

标签: php mysql laravel eloquent

我是Laravel和Eloquent的新手,我正在努力创建一个足球比赛计划 现在我有4个表(带有一些示例条目):

团队(所有团队)

+---------+-----------+
| team_id | team_name |
+---------+-----------+
|       1 | Arsenal   |
|       2 | Chelsea   |
+---------+-----------+

比赛(所有比赛)

+----------------+------------------+
| competition_id | competition_name |
+----------------+------------------+
|              1 | Premier League   |
+----------------+------------------+

时间表(比赛时间表)

+----+----------------+----------+--------------+--------------+-----------+-----------+
| id | competition_id | matchday | home_team_id | away_team_id | home_goal | away_goal |
+----+----------------+----------+--------------+--------------+-----------+-----------+
|  1 |              1 |        1 |            1 |            2 |         3 |         2 |
|  2 |              1 |        2 |            2 |            1 |         0 |         3 |
+----+----------------+----------+--------------+--------------+-----------+-----------+

schedule_teams(将计划teamid与team_id和schedule_team_id上的团队ID匹配)

+----+------------------+----------------+----------+
| id | schedule_team_id | competition_id | teams_id |
+----+------------------+----------------+----------+
|  1 |                1 |              1 |        1 |
|  2 |                2 |              1 |        2 |
+----+------------------+----------------+----------+

以下是我目前的课程:

Schedule.php

public function competition()
{
   return $this->belongsTo(Competition::class, 'competition_id', 'competition_id');
}

Competition.php

public function schedule()
{
   return $this->hasMany(Schedule::class, 'competition_id', 'competition_id');
}

$id = \request('competition_id');
$schedule = Schedule::where('competition_id', $id)->with('competition')->get();

我从日程安排获得了主页和客场ID的时间表。 现在的问题是,如何通过schedule_teams表将团队表中的条目输入到特定的home和away id,例如home_team_id = 1:
 home_team_id(= 1) - > schedule_team_id(= 1)和competition_id(= 1) - >球队(阿森纳)

我希望计划中的数据和集合中的关联团队在刀片中输出。

任何人都可以帮助或给我足球数据库的改进技巧吗?

1 个答案:

答案 0 :(得分:1)

您应该使用data1$a3 <- NA for(i in 1:nrow(data2)){ for(j in 1:nrow(data1)){ if(data1[j,1] == data2[i,2]){ data1[j,3] <- data2[i,1] } } } 关系。

如果你创建说hasManyThrough,然后像下面那样。

Schedule\Team

现在,在public function schedule() { $this->belongsTo(Schedule::class, 'schedule_id'); } public function team() { $this->belongsTo(Team::class, 'team_id'); } 课程中,您可以拥有以下内容。

Schedule

还应注意,您的日程安排团队中不需要public function teams() { $this->hasManyThrough(Team::class, Schedule\Team::class, 'schedule_id'); } 。由于一个团队属于一个属于竞争的时间表,你可以这样做。

如果您还希望competition_id了解其日程安排,可以将其添加到Team

Team

public function schedules() { return $this->hasManyThrough(Schedule::class, Schedule\Team::class); } 类基本上是一个数据透视表的美化表示,但是将它作为模型,可以让你在将来扩展它。它还有助于保持整洁。

希望这是有道理的。