Laravel 中同一模型的多个关系
Multiple relations to same model in Laravel
我在 Eloquent 中有一个多对多关系。
架构:
templates modules module_template
- id - id - module_id
- name - content - template_id
- order
但是,我需要使单个模板能够多次包含同一模块。我该怎么做?
示例module_template
:
module_id | template_id | order
1 | 42 | 1
4 | 42 | 2
1 | 42 | 3
$template->modules()->detach($moduleId)
会 detach 与模型的所有关系,对吧?假设甚至有可能首先 attach
他们。
如果您将 module_template 定义为自己的 Eloquent 模型 ModuleTemplate
,您将能够做到这一点
这样您就可以在 table 中插入和删除行,而无需依赖 attach() 和 detach() 及其检查。
您可以 attach
多次,没问题。但是 detach
将删除所有关联。 (当然你的 table 不能应用 FK1,FK2
unique/primary 约束)
但是,不要害怕 :) 您仍然可以手动完成:
$moduleId = 1;
$template->modules()
->newPivotStatementForId($moduleId)
->where('order', 3)
->delete()
我在 Eloquent 中有一个多对多关系。
架构:
templates modules module_template
- id - id - module_id
- name - content - template_id
- order
但是,我需要使单个模板能够多次包含同一模块。我该怎么做?
示例module_template
:
module_id | template_id | order
1 | 42 | 1
4 | 42 | 2
1 | 42 | 3
$template->modules()->detach($moduleId)
会 detach 与模型的所有关系,对吧?假设甚至有可能首先 attach
他们。
如果您将 module_template 定义为自己的 Eloquent 模型 ModuleTemplate
这样您就可以在 table 中插入和删除行,而无需依赖 attach() 和 detach() 及其检查。
您可以 attach
多次,没问题。但是 detach
将删除所有关联。 (当然你的 table 不能应用 FK1,FK2
unique/primary 约束)
但是,不要害怕 :) 您仍然可以手动完成:
$moduleId = 1;
$template->modules()
->newPivotStatementForId($moduleId)
->where('order', 3)
->delete()