我有两个模型:
- 团队
- 游戏(在两场比赛之间进行)
Game 模型有两个指向 Team 模型的外键 - team1_id 和 team2_id。
这是团队模型的代码:
class Team extends Eloquent
{
protected $table = 'team';
protected $fillable = [
'name',
'color',
'year'
];
public function games()
{
return $this->hasMany(\App\Models\Game::class);
}
}
游戏模型代码:
class Game extends Eloquent
{
protected $table = 'game';
protected $casts = [
'team1_id' => 'int',
'team2_id' => 'int'
];
protected $fillable = [
'team1_id',
'team2_id',
'location',
'start_at'
];
public function team1()
{
return $this->hasOne(\App\Models\Team::class, 'team1_id');
}
public function team2()
{
return $this->hasOne(\App\Models\Team::class, 'team2_id');
}
}
我收到一条错误消息,指出找不到该列。
return $this->hasMany(\App\Models\Game::class, 'team1_id');
这可行,但问题是我想根据 team1_id 和 team2_id 获取游戏。
最佳答案
您必须指定用于引用该关系的外键和本地键
public function localTeam()
{
return $this->belongsTo(\App\Models\Team::class, 'id', 'team1_id');
}
public function foreignTeam()
{
return $this->belongsTo(\App\Models\Team::class, 'id', 'team2_id');
}
关于php - Eloquent:一个表中的两个外键指向同一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46946175/