我有两种模式:
游戏模型有两个指向团队模型的外键 - 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获取游戏。
答案 0 :(得分:0)
您必须指定外键和用于引用该关系的本地密钥
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');
}