首页 文章

如何设置Eloquent关系以使用3向数据透视表

提问于
浏览
0

我有一个3路数据透视表,它将角色与特定组织的用户联系起来 . 以下是相关表格的设置方法:

//users table
Schema::create('users', function($table)
{
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->string('username', 30)->index();
    //more (irrelevant) fields here
    $table->timestamps();
});

//roles table
Schema::create('roles', function(Blueprint $table)
{
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->string('name', 100)->index();
    $table->string('description', 255)->nullable();
    $table->timestamps();
});

//organizations table
Schema::create('organizations', function(Blueprint $table)
{
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->string('name', 255);
    $table->string('slug', 100);
    $table->text('description');
    $table->timestamps();
});

//organization user role table
Schema::create('organization_user_role', function(Blueprint $table)
{
    $table->engine = 'InnoDB';

    $table->increments('id');
    $table->integer('role_id')->unsigned()->index();
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    $table->integer('user_id')->unsigned()->index();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->integer('organization_id')->unsigned()->index();
    $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
    $table->timestamps();
});

每个用户可以属于一个或多个组织,具有一个或多个角色 . 角色同时与用户和组织联系在一起 . 也就是说,用户必须在组织中具有角色才能与其相关联 .

这似乎不适合传统的多对多关系枢轴表的模型,它与Eloquent开箱即用 . Eloquent可以处理这种关系,还是需要一个专门处理这种关系的新模型?有人可以告诉我用户,组织和角色模型将3向数据透视表关系与Eloquent联系在一起的样子吗?

1 回答

相关问题