Laravel 5 Eloquent 多对多二次 table

Laravel 5 Eloquent Many to Many 2ndary table

我有一个问题,我不确定如何解决,甚至不知道如何找到答案。

我有一个多对多关联的公司模型和用户模型。

我想要一个user_pinstable。一个用户可以属于多个公司,因此在每个公司中都有不同的 PIN。 Pin 在一个公司内是唯一的,一个公司内的两个用户不能拥有相同的 Pin。不同公司的用户可以拥有相同的

所以对公司来说是一对多,对用户来说是一对多,但总的来说就是多对多,我不确定这样是否有意义。

我将 table 设置为

Schema::create('user_pins', function (Blueprint $table) {
 $table->integer('user_id')->unsigned();
 $table->integer('company_id')->unsigned();
 $table->string('pin');

 $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
 $table->foreign('company_id')->references('id')->on('companies')->onUpdate('cascade')->onDelete('cascade');

 $table->primary(['user_id', 'company_id', 'pin']);
});

我如何在模型中关联这个 table 并使用 Eloquent 到 access/create/update 它以便它存储用户和公司?

首先,我会将名称更改为 company_user,以便它遵循与 Laravel 开箱即用的相同命名约定。 (你不必这样做,因为你可以在关系中指定枢轴 table 名称,但如果没有理由坚持使用 user_pin ,那么遵循惯例是有意义的 :) )

然后我会删除主键,使其不再是所有 3 个字段的组合,并将其放在 company_iduser_id.

最后,由于 PIN 只需要对一家公司来说是唯一的,我只需将唯一索引放在这两列上,例如

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

    $table->integer('company_id')->unsigned()->index();
    $table->integer('user_id')->unsigned()->index();
    $table->string('pin');

    $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
    $table->foreign('company_id')->references('id')->on('companies')->onUpdate('cascade')->onDelete('cascade');

    $table->primary(['company_id', 'user_id']);
    $table->unique(['company_id', 'pin']);
});

然后对于模型中的关系,我会有类似的东西:

return $this->belongsToMany('App\Company')->withPivot('pin');

return $this->belongsToMany('App\User')->withPivot('pin');

枢轴使用示例

一家公司的所有用户 Pin 图:

$company->users->lists('pivot.pin');

特定公司的用户图钉

$user->companies()->where('id', $id)->get()->pivot->pin;

第一个公司关系的用户 pin:

$user->companies->first()->pivot->pin;

希望对您有所帮助!