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

dmag's avatar
Level 6

Should I use pivot or regular table?

I have two tables and I need to store a value that relates to the two tables, so I store it in third table:

// Table C
| id | table_a_id | table_b_id | value |

Should I make Table C a pivot table or regular table, meaning having BelongsToMany or HasMany in Table A and B? What would be the difference? Or I'm missing something?

0 likes
2 replies
LaryAI's avatar
Level 58

In this case, it would be better to use a regular table instead of a pivot table. A pivot table is used when you have a many-to-many relationship between two tables, and you need to store additional information about that relationship. In this case, you have a one-to-many relationship between Table A and Table C, and a one-to-many relationship between Table B and Table C.

To set up the relationships, you would use the following code:

// Table A model
class TableA extends Model
{
    public function tableCs()
    {
        return $this->hasMany(TableC::class);
    }
}

// Table B model
class TableB extends Model
{
    public function tableCs()
    {
        return $this->hasMany(TableC::class);
    }
}

// Table C model
class TableC extends Model
{
    public function tableA()
    {
        return $this->belongsTo(TableA::class);
    }

    public function tableB()
    {
        return $this->belongsTo(TableB::class);
    }
}

With this setup, you can easily access the related models:

$tableA = TableA::find(1);
$tableCs = $tableA->tableCs;

$tableB = TableB::find(1);
$tableCs = $tableB->tableCs;

$tableC = TableC::find(1);
$tableA = $tableC->tableA;
$tableB = $tableC->tableB;
tisuchi's avatar

@dmag I prefer to use a regular table in your scenario.

1 like

Please or to participate in this conversation.