php - Eloquent:一个表中的两个外键指向同一个表

标签 php laravel eloquent

我有两个模型:

  • 团队
  • 游戏(在两场比赛之间进行)

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/

相关文章:

laravel - 在 laravel jetstream 中禁用浏览器 session

php - Laravel - Twig View 中的 print_r

database - 使用对象过滤查询集

mysql - Laravel Eloquent 关系(需要建议)

php - 仅在一页上动态调整 div 大小?

php - 我在 ionic 3 中遇到错误 : Runtime Error Unexpected token < in JSON at position 0 when posting to php from ionic3

logging - Laravel 请求和响应日志记录

php - 中间表的 Eloquent 模型关系

php - 在带有 UNION 关键字的 mysql 查询中使用按 DESC 或 ASC 排序

php - mysqli_connect 没有错误报告