简体   繁体   English

Laravel - 如何使用其属性克隆关系数据透视图?

[英]Laravel - How to clone a relationship pivot with its attributes?

I have a many to many relationship in laravel with a pivot object/table. 我在laravel中有一个多对多的关系,带有一个数据透视对象/表。 I want to create a copy of one entry in this table, mantaining all the pivot properties (I have extra attributes for the relationship) and creating a new id. 我想在此表中创建一个条目的副本,保留所有数据透视属性(我有关系的额外属性)并创建一个新的ID。

Is it possible with laravel or should I just hack some raw sql into the database? 是否可以使用laravel或者我应该将一些原始sql入侵数据库?

In Laravel 5.4, if you want to clone a many-to-many Model, including its relationships and extra attributes in the pivot table, you need to amend the original solution provided in https://stackoverflow.com/a/34032304/309383 like so: 在Laravel 5.4中,如果要克隆多对多模型,包括其在数据透视表中的关系和额外属性,则需要修改https://stackoverflow.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);
    }
}

Note that this only applies to many-to-many relationships with pivot tables. 请注意,这仅适用于与数据透视表的多对多关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM