Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GonG's avatar
Level 1

Two Same Pivot Tables But Different in Attributes

Hi, lets say I have two basic databases structure:

instructions id description rawmaterials id name

These two models will form two kinds of pivot table, 1. I need a table that will store serial number of rawmaterial put in each instruction, for example:

| id | instruction_id | rawmaterial_id | serial |

|----|-----------------------|-------------------------|----------|

| 1 | 1 | 1 | A1 |

| 2 | 1 | 2 | A2 |

| 3 | 2 | 1 | A3 |

| 4 | 2 | 2 | A4 |

each instruction must have all rawmaterial attach to itself and serial attribute can be different in each instruction.

Now, the problem is that I also need this kind of structure but the different is that there can be multiples time of instruction store base on "fill_times" attribute, for example:

| id | instruction_id | rawmaterial_id | fill_times | fill_qty |

|----|-----------------------|-------------------------|----------------|------------|

| 1 | 1 | 1 | 1 | 10 |

| 2 | 1 | 1 | 2 | 15 |

| 3 | 1 | 2 | 1 | 10 |

| 4 | 2 | 1 | 1 | 5 |

| 5 | 2 | 2 | 2 | 6 |

The above table means that, for example row 1, instruction 1 fill first time of rawmaterial 1 by 10 qty, and row 2 is instruction 1 fill second time of rawmaterial 2 by 15 and so on.

What do you suggest to do this kind of structure in Laravel ?

PS. Sorry, if the question is kinds of confused and too long, cause i don't know how to explain this well by writing. Thank you

0 likes
4 replies
MThomas's avatar
MThomas
Best Answer
Level 35

I think this might help you: http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables

You can set additional fields on a pivot table (eg. fill_times, fill_qty) and specify the name of the pivot table in the relation (you have two tables so you need two separate relationships in your models:

public function rawmaterials() {
    return $this->belongsToMany('Rawmaterial', 'institution_rawmaterial'); // the table name should not be needed here
}

public function rawmaterialsExtended() {
    return $this->belongsToMany('Rawmaterial', 'institution_rawmaterial_extended')->withPivot('fill_times', 'fill_qty');
}

And ofcourse you need to set similar relations on your Intitution model.

pmall's avatar

Yes you can do many relations between a couple of tables, with different query.

GonG's avatar
Level 1

Oh, thank you very much. After I looked at your answer, I think is this simple ? haha!! Because at first, I think this is gonna be very complicated.

Please or to participate in this conversation.