Laravel Eloquent - 具有两个 ID 列的多态关系

Laravel Eloquent - Polymorphic Relationships With Two ID Columns

我的游戏table中有以下列:

-match_type
-team_one_id
-team_two_id

match_type 列的值可以是 singlesdoubles.我还有两个额外的 table 叫做 userspairs.

如果match_type的值是singles,我想要team_one_idteam_two_id 列与 users table 相关。如果 match_type 的值是 doubles,我希望这两列与 pairs table.

我如何使用 Eloquent 执行此操作 - 两列的关系取决于类型的值?

我不得不覆盖 Laravel 的 Model class 中的 morphMany() 方法,以允许自定义列名用于多态关系。默认情况下,Laravel 使用 _type_id 后缀来标识多态关系所需的列。这两列还必须具有相同的前缀(即 reference_typereference_id).

在我的 UserPair 模型中,我有以下内容:

// Overwrite morphMany() so we can use custom columns
public function morphMany($related, $name, $type = null, $id = null, $localKey = null){

    $instance = new $related;
    $table = $instance->getTable();
    $localKey = $localKey ? : $this->getKeyName();
    return new MorphMany($instance->newQuery(), $this, $table . '.' . $type, $table . '.' . $id, $localKey);

}

这让我可以使用 Games table 建立关系:

// Defines the relationship between this table and the games table through the team_one_id column
public function game_team_one(){

    return $this->morphMany('App\Models\Game', null, 'match_type', 'team_one_id');

}

// Defines the relationship between this table and the games table through the team_two_id column
public function game_team_two(){

    return $this->morphMany('App\Models\Game', null, 'match_type', 'team_two_id');

}

然后,在 Game 模型中,您将使用 morphTo() 填充前三个可选参数(以覆盖默认列名)来建立我们的多态关系:

// Defines the relationship between this table and the users / pairs table through the team_one_id column
public function team_one(){

    return $this->morphTo(null, 'match_type', 'team_one_id');

}

// Defines the relationship between this table and the users / pairs table through the team_two_id column
public function team_two(){

    return $this->morphTo(null, 'match_type', 'team_two_id');

}