我有四个表,分别是机构,表单,form_institution(数据透视表)和form_institution_attributes。这是迁移:
机构表:
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');
});
现在,当我调用机构表和机构 - >表单参数时,我想获得带有数据透视表的form_institution_attribute(子表)。但我无法做到这一点?
如何在数据透视表下添加表作为一对多关系?
答案 0 :(得分:2)
您应该可以使用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'.
...
]);
}