Laravel - 如何克隆关系枢轴及其属性?

rap*_*dko 5 php laravel laravel-5

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

laravel 可以吗?还是我应该将一些原始 sql 写入数据库?

Dan*_*n H 6

在 Laravel 5.4 中,如果要克隆多对多模型,包括其关系和数据透视表中的额外属性,则需要修改/sf/answers/2382261311/中提供的原始解决方案像这样:

$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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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