dongqie4402 2016-10-01 22:52
浏览 69

在Laravel 5.3中使用hasMany相关模型克隆模型

(Looks like I solved my own problem, if only someone could answer question in the Update 1 and check my own solution for the problem in Update 2. Thank you.) Trying to clone Invoice model with related Items. Getting Call to undefined method Illuminate\Database\Query\Builder::associate() error. Any help is greatly appreciated!

Invoice.php

public function items(){
    return $this->hasMany('App\Item');
}

Item.php

public function invoice(){
    return $this->belongsTo('App\Invoice');
}

InvoiceController.php

public function copy(Invoice $invoice){
    $copy = $invoice->replicate(['number']);
    foreach($invoice->items as $item) $copy->items()->associate($item);
    $copy->push();
    return redirect('/invoices/' . $copy->id . '/edit')->with('alerts', ['Invoice has been copied']);
}

Update 1

I guess, I semi-figured this out. Parent cloned model should be saved first to receive an ID before calling for saveMany on children nodes. Looks like push method cannot be used here either. I am still puzzled, why I cannon use associate and push methods in this scenario...

Update 2

Turns out this method was not creating cloned items, instead, it was updating the ones it was trying to clone, which is weird... What I did is replicate items inside a loop (replication does not exists in relations like belongsTo). So my final code is:

public function copy(Invoice $invoice){
    $copy = $invoice->replicate(['number', 'url_key']);
    $copy->url_key = strtolower(str_random(8));
    $copy->save();
    foreach($invoice->items as $item) $copy->items()->save($item->replicate(['type_id']));
    return redirect('/invoices/' . $copy->id . '/edit')->with('alerts', ['Invoice has been copied']);
}
  • 写回答

1条回答 默认 最新

  • donglei1616 2016-10-03 17:01
    关注

    You need to call save() instead of associate():

    $copy->items()->save($item);
    

    or saveMany() that internally calls save() for a collection of models:

    $copy->items()->saveMany($invoice->items);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题