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

VaughnKennett's avatar

Many to Many Table - same table?

Wondering if this is possible - would like a single M-M table of cascading questions:

Q1 Title of Question 1
	Q2 Title of Question 2
	Q3 Title of Question 3
		Q4 Title of Question 4
Q5 Title of Question 5

obviously the table structure could be a combination of multiple seperate tables - for each level:

Q1 Title of Question One
	Q1-1 Title of Question 1-1
	Q1-2 Title of Question 1-2
		Q1-2-1 Title of Question 1-2-1
Q2 Title of Question 2

but I would like a single table of questions, that point to themselves? i.e. Table containing

Q1 - with Q2, and Q3
Q3 - with Q4

i.e a single table of cascading items.

The M-M relationship has the issue of the question_question pivot table containing 2 ids of the same name, question_id and question_id which causes the obvious error.

Has anybody used this approach of a M-M table, pointing to itself? Or is this obviously not possible?

0 likes
9 replies
VaughnKennett's avatar

Hi webrobert The structure is parent-child....->no limit on levels, but all items are in the same table, does that make sense?

webrobert's avatar

@vaughnkennett, You just need a parent_id column and you can create a relationship to self. In the model

    public function parent()
    {
        return $this->hasOne(Question::class,'id', 'parent_id');
    }
    
    public function children()
    {
        return $this->hasMany(Question::class, 'parent_id', 'id');
    }

But I’m on my phone right now and I may have The syntax wrong here for the model.

VaughnKennett's avatar

THanks webrobert - will test it out, appreciate your quick response.

VaughnKennett's avatar

Thanks Silencebringer - will do some reading, and test this out too. Appreciate the links to subject matter.

Please or to participate in this conversation.