I have a four table which are institutions, forms, form_institution(pivot table) and form_institution_attributes. Here is migrations :
Institution Table :
public function up() {
Schema::create('institutions', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->softDeletes();
$table->timestamps();
});
}
Institution model :
public function forms() {
return $this->belongsToMany(Form::class, 'form_institution');
}
Form Table :
public function up() {
Schema::create('forms', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->softDeletes();
$table->timestamps();
});
}
Form Model :
public function institutions() {
return $this->belongsToMany(Institution::class, 'form_institution');
}
Form Institution Pivot Table :
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');
});
Everything is ok till here. But i need to add one more table which is attribute table and it's relationship between pivot table (one-to-many)
Here is table :
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');
});
Now, when i call the institution table and institution->forms parameter, i want to get form_institution_attribute (sub-table) with pivot table. But i couldn't do this ?
How can i add table under pivot table as a one-to-many relation ?
You should be able to use the HasManyThrough type of relationship.
However, I think the best solution would be to add these attributes to extra columns that you create in your 'form_institution' table and then retrieve them much more easily by adding the withPivot method to your relationship definitions.
So that would look like this:
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'.
...
]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With