【问题标题】:Laravel - How to clone a relationship pivot with its attributes?Laravel - 如何克隆具有属性的关系枢轴?
【发布时间】:2025-12-07 02:20:02
【问题描述】:

我在 laravel 中与枢轴对象/表有多对多关系。 我想在这个表中创建一个条目的副本,维护所有的数据透视属性(我有额外的关系属性)并创建一个新的 id。

是否可以使用 laravel 或者我应该将一些原始 sql 破解到数据库中?

【问题讨论】:

  • 你能举一些例子吗,你想做什么?

标签: php laravel laravel-5


【解决方案1】:

在 Laravel 5.4 中,如果你想克隆一个多对多模型,包括它的关系和数据透视表中的额外属性,你需要修改 https://*.com/a/34032304/309383 中提供的原始解决方案,如下所示:

$model = User::find($id);

$model->load('invoices');

$newModel = $model->replicate();
$newModel->push();

// Once the model has been saved with a new ID, we can get its children
foreach ($newModel->getRelations() as $relation => $items) {
    foreach ($items as $item) {
        // Now we get the extra attributes from the pivot tables, but
        // we intentionally leave out the foreignKey, as we already 
        // have it in the newModel
        $extra_attributes = array_except($item->pivot->getAttributes(), $item->pivot->getForeignKey());
        $newModel->{$relation}()->attach($item, $extra_attributes);
    }
}

请注意,这仅适用于与数据透视表的多对多关系。

【讨论】: