用关系复制记录

时间:2018-10-03 11:46:37

标签: mysql laravel laravel-5

Hospital Table
id | name | address
-----------------------

Hospital_Key Table
id | hospital_id(fk of Hospital Table) | type
-----------------------------------------------

Hospital_Column Table
id | hospital_id(fk of Hospital Table) | name
---------------------------------------------------------

Hospital_fields Table

id | Hospital_Key_id(fk of Hospital_Key Table) | Hospital_col_id(fk of Hospital_Column Table) | data
------------------------------------------

---------------------------------------------------------------

我想复制/克隆任何记录和子记录的所有数据 例如医院表的一条记录 从医院获取数据,Hospital_Key,Hospital_Column 并使用新的主键复制同一表中的所有数据。

    $input = $request->all();

    $library = Library::with('key', 'col','key.field')->findOrFail($input['lib_id']);
    $new = $library->replicate();
    $new->user_id = Auth::id();
    $new->privacy_setting = 'Private';
    $new->push();

    $library->relations = [];

    $library->load('key', 'col','key.field');
    $relations = $library->getRelations();

    foreach ($relations as $relation => $items) {

        foreach ($items as $item) {

            $newfield = $new->{$relation}()->create($item->toArray());
        }
    }

上面的代码确实复制了Hospital,Hospital_Key,Hospital_Column的记录 上面的代码不会复制Hospital_fields(grandchild)的记录

相关信息:医院hasmany Hospital_Key,医院hasmany Hospital_Column, 医院_主要哈斯曼医院_领域 如何复制Hospital_fields表数据

0 个答案:

没有答案