我正在开发一个可以让人们观看体育比赛的应用程序。这些表具有复合主键。表的相关属性如下所示:
| Game | Team | League_Team |
|---------------------------|-------------|----------------|
| id (PK) | id (PK) | league_id (PK) |
| league_id (PK) | name | team_id (PK) |
| home_id (season_team_id) | ... | season_team_id |
| guest_id (season_team_id) | | ... |
| ... | | |
| ... | | |
所以我的目标是将所有游戏与特定的主场和客队一起使用...所以它应该像这样Game::with('homeTeam')->with('guestTeam')->....;
如何获得这种关系?我尝试过hasOneThrough
,但不知道它如何与复合主键配合使用!
感谢您的帮助!
编辑
除$primaryKey
属性外,所有模型均为空。
游戏模型
protected $primaryKey = ['id', 'league_id'];
public function homeTeam() { // ... }
public function up()
{
Schema::create('basketball_games', function (Blueprint $table) {
$table->unsignedInteger('id');
$table->unsignedInteger('league_id')->nullable();
$table->dateTime('date');
$table->unsignedInteger('home_id');
$table->unsignedInteger('guest_id');
$table->primary(['id','league_id']);
// Foreign Keys
$table->foreign('league_id')->references('id')->on('basketball_leagues');
$table->timestamps();
});
}
团队模型
空
public function up()
{
Schema::create('basketball_teams', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
联赛团队
protected $primaryKey = ['league_id','team_id'];
public function up()
{
Schema::create('basketball_league_teams', function (Blueprint $table) {
$table->unsignedInteger('league_id');
$table->unsignedInteger('team_id');
$table->unsignedInteger('season_team_id');
$table->string('name');
$table->timestamps();
$table->primary(['league_id','team_id']);
// Foreign Keys
$table->foreign('league_id')->references('id')->on('basketball_leagues');
$table->foreign('team_id')->references('id')->on('basketball_teams');
});
}