Martti Laine
Martti Laine

Reputation: 12995

Multiple relations to same model in Laravel

I have a many-to-many relationship in Eloquent.

Schema:

templates       modules         module_template
- id            - id            - module_id
- name          - content       - template_id
                                - order

However, I need to make it possible for a single template to include the same module multiple times. How would I do that?

Example module_template:

module_id | template_id | order
1         | 42          | 1
4         | 42          | 2
1         | 42          | 3

$template->modules()->detach($moduleId) would detach all relations to the model, right? Assuming it would even be possible to attach them in the first place.

Upvotes: 2

Views: 946

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

You can attach multiple times, no problem with that. However detach will remove all the associations. (Of course your table can't have FK1,FK2 unique/primary constraint applied)

But, fear not :) You can still do it manually:

$moduleId = 1;

$template->modules()
   ->newPivotStatementForId($moduleId)
   ->where('order', 3)
   ->delete()

Upvotes: 2

Margus Pala
Margus Pala

Reputation: 8673

You will be able to do that if you define module_template as its own Eloquent Model ModuleTemplate

That way you can insert and remove rows in the table without relying on the attach() and detach() and their checks.

Upvotes: 1

Related Questions