Laravel 数据模型中多对多 table 关系的多个 "statuses"?最好的方法?

Multiple "statuses" for many-2-many table relationship in a Laravel Data Model? Best approach?

我是 Laravel 的新手(才编码几个月)。我创建了一个数据库模型,它通过枢轴 table.

连接两个 tables "Players" 和 "Teams"
class Player extends Model
{
    public function teams()
    {
        # With timetsamps() will ensure the pivot table has its created_at/updated_at fields automatically maintained
        return $this->belongsToMany('p4\Team')->withTimestamps();
    }
}


class Team extends Model
{
    public function players()
    {
        return $this->belongsToMany('p4\Player')->withTimestamps();
    }
}

玩家可以是(许多)团队的成员,"own" 个团队,"recruited" 个团队,"rejected" 个团队。战队和选手都可以对这些状态中的每一个发起请求,允许对方confirm/reject。在每种情况下,它们都应该被 linked 并且只能占据四种状态中的一种。 link 这两个 table 最好的方法是什么,这样任意两个实例之间的关系都可以给出 4 "statuses"?

我需要让用户(在这个开放的 management/recruitment 环境中控制球队和球员)能够在每个 "statuses" 中进行 request/approve 分类。

让我印象深刻的是,最简洁的方法是使用单个枢轴 table,"assigns" 这些给定状态到每个 linked ID 对。然而,我只看到了执行这个概念的更简单的例子,因此我不确定最好的方法是什么。我会很感激这里的一些指导。

Schema::create('player_team', function (Blueprint $table) {

    $table->increments('id');
    $table->timestamps();

    # `book_id` and `tag_id` will be foreign keys, so they have to be unsigned
    #  Note how the field names here correspond to the tables they will connect...
    # `book_id` will reference the `books table` and `tag_id` will reference the `tags` table.
    $table->integer('player_id')->unsigned();
    $table->integer('team_id')->unsigned();

    # Make foreign keys
    $table->foreign('player_id')->references('id')->on('players');
    $table->foreign('team_id')->references('id')->on('teams');
});

*再一次,我很新鲜。抱歉,如果这有一个明显的解决方案,我只是想念。

如果我没理解错的话,您可以将 status 列添加到数据透视表 table:

$table->tinyInteger('status')->unsigned();

不要忘记将 withPivot() 添加到关系中:

return $this->belongsToMany('p4\Player')->withPivot('status')->withTimestamps();

您可以使用 pivot 访问此列,并通过将数组添加到 attach()detach() 方法来设置或取消设置它:

$team->players()->attach($playerId, ['status' => 3]);

在文档中阅读更多相关信息:

https://laravel.com/docs/5.3/eloquent-relationships#many-to-many https://laravel.com/docs/5.3/eloquent-relationships#inserting-and-updating-related-models