简体   繁体   English

如何在 Laravel 中同时保存模型和相关模型?

[英]How can I save model and related models at the same time in Laravel?

My current version below, its work but in my code;下面是我当前的版本,它的工作但在我的代码中; first I save the model and after the related model.首先我保存模型,然后保存相关模型。

    // Model        
    $pdf= new Canvas;
    $pdf->numero = $data['number'];
    $pdf->project = $data['title'];
    $pdf->date = $data['date'];
    $pdf->user_id = auth()->id();
    $pdf->type = 'type1';
        
    // Related model  
    $version = new Version;
    $version->json = 'teste2.json';
    $version->version = 1;
    $version->updated_by = auth()->id();
    
    //persist
    $canvas->save();
    $canvas->versions()->save($version);

What I need is: how to save both model at the same time?我需要的是:如何同时保存两个模型?

  1. Create model创建模型
  2. Create related model创建相关模型
  3. Persist both model (related model get automatically the model_id)保留两个模型(相关模型自动获取model_id)
  4. if any problem happened, both model will not crated.如果发生任何问题,两个模型都不会被装箱。

thanks so much非常感谢

you can user this你可以使用这个

$pdf = Canvas::create([
    'numero'  => $data['number'],
    'project' => $data['title'],
    'date'    => $data['date'],
   ...
]);

$pdf->versions()->create([
     'json'    => 'teste2.json',
     'version' => 1,
     ....

 ]);

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

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