【发布时间】:2025-12-19 02:30:15
【问题描述】:
我创建了以下数据库结构来管理不同批次的不同服务内容,因为这个结构也必须为子服务复制,所以我决定在 Laravel 中使用“多对多多态关系”。
要在表“service_and_relatives_contents”中创建一个新记录,并在表“service____relative_content_batch_a”(我的数据透视表)中创建另一个关联记录,我使用了:
$service -> relatives() -> create($arrRelatives)
该代码的问题是我无法在我的数据透视表中填充“batches_id”字段。 出于这个原因,我使用了以下代码:
$relativeId = $service->relatives()->create($arrRelatives)->id;
$service->relatives()->updateExistingPivot($relativeId,['batches_id'=>$keyRelatives]);
它运行良好,但它是同时创建和关联记录的正确方法?
请将此作为示例,我将使用 laravel 约定作为表名和外键作为实时版本。
【问题讨论】:
-
试试 '$service->relatives->create($arr)'
-
@HasanTıngır 它返回错误“方法创建不存在。”
-
@HasanTıngır 另一种可能是:$relativeId=$relative->create($arrRelatives)->id; $service->relatives()->attach($relativeId,['batches_id'=>$keyRelatives]);
标签: php laravel laravel-5 many-to-many