我有四个表,分别是机构、表单、表单机构(透视表)和表单机构属性。以下是迁移:
机构表:

public function up() {
     Schema::create('institutions', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name', 255);
         $table->softDeletes();
         $table->timestamps();
     });
 }

制度模式:
public function forms() {
    return $this->belongsToMany(Form::class, 'form_institution');
}

表格:
public function up() {
    Schema::create('forms', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name', 255);
        $table->softDeletes();
        $table->timestamps();
    });
}

表单模型:
public function institutions() {
    return $this->belongsToMany(Institution::class, 'form_institution');
}

表单机构透视表:
Schema::create('form_institution', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('institution_id')->unsigned();
    $table->integer('form_id')->unsigned();

    $table->foreign('institution_id')->references('id')->on('institutions');
    $table->foreign('form_id')->references('id')->on('forms');
});

到这里为止一切都很好。但我需要再添加一个表,它是属性表,并且是透视表(一对多)之间的关系。
这是桌子:
Schema::create('form_institution_attributes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('form_institution_id')->unsigned();
            $table->integer('field_name_id')->unsigned();
            $table->integer('input_type_id')->unsigned();
            $table->string('field_caption');
            $table->softDeletes();
            $table->timestamps();

            $table->foreign('form_institution_id')->references('id')->on('form_institution');
        });

现在,当我调用institution table和institution->forms参数时,我想用pivot table获得form_institution_属性(子表)。但我做不到?
如何将透视表下的表作为一对多关系添加?

最佳答案

您应该能够使用HasManyThrough类型的关系。
不过,我认为最好的解决方案是将这些属性添加到在“form_institution”表中创建的额外列中,然后通过将WithPivot方法添加到关系定义中来更容易地检索它们。
这样看来:

public function forms() {
    return $this->belongsToMany(Form::class, 'form_institution')
        ->withPivot([
            'field_name_id',
            'field_caption'.
            ...
        ]);
}

public function institutions() {
    return $this->belongsToMany(Institution::class, 'form_institution')
        ->withPivot([
            'field_name_id',
            'field_caption'.
            ...
        ]);
}

关于php - laravel一对多在数据透视表上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46887916/

10-10 08:22