如何使用 laravel 8 同时保存一对多关系数据

Posted

技术标签:

【中文标题】如何使用 laravel 8 同时保存一对多关系数据【英文标题】:How to save One to Many relationqhip data at same time using laravel 8 【发布时间】:2021-08-29 01:55:10 【问题描述】:

我正在尝试将数据存储到数据库中,但遇到了一种情况,我不知道这样做是否可行。

所以我在数据库中有两个下表

public function up()
    
        Schema::create('castings', function (Blueprint $table) 
            $table->increments('id_casting');
            $table->string('nom');
            $table->string('prenom');
            $table->string('cine');
            $table->string('date_naissance');
            $table->integer('lieu_naissance');
            $table->string('mineur');
            $table->integer('id_representant')->unsigned();
            $table->timestamps();
            $table->foreign('id_representant')->references('id_representant')->on('representants');
        );
    

还有表格代表:

public function up()
    
        Schema::create('representants', function (Blueprint $table) 
            
            $table->increments('id_representant');
            $table->string('nom_prenom');
            $table->string('cine');
            $table->string('lien_casting');
            $table->integer('actif');
            $table->timestamps();
        );
    

我的模特:

class Casting  Model

    use HasFactory;
   
extends     protected $fillable = ["id_casting",
        "nom", "prenom" , "cine" , "date_naissance","lieu_naissance" ,"mineur"
    ];


    public function representants()

    return $this->belongsTo('App\Representant');



还有模特代表:

class Representant extends Model

    use HasFactory;

     protected $fillable = ["id_representant",
            "nom_prenom", "cine" , "lien_casting","actif"
    ];


    function castings() 

    return $this->hasMany('Casting');



我有以下表格:

<form id="castingform" method="post" action="castingss"   enctype="multipart/form-data">
   
                     csrf_field() 
                    <input type="hidden" id="id_hidden" name="id" />
                    <div class="form-row">
                       <div class="form-group col-md-6">
                          <label for="casting_name">Nom</label>
                          <input type="text" class="form-control" id="nom" name="nom" placeholder="Nom" >
                         
                       </div> 
                       <div class="form-group col-md-6">
                          <label for="casting_name">Prénom</label>
                          <input type="text" class="form-control" id="prenom" name="prenom" placeholder="Prenom" >
                     
                       </div>
                       </div>
                     <div class="form-row">
                       <div class="form-group col-md-6">
                          <label for="casting_cin">CIN</label>
                          <input type="text" class="form-control" id="cine" name="cine" placeholder="Cin">
                       </div>
                     </div>
                     <div class="form-row">
                       <div class="form-group col-md-6">
                          <label for="casting_date_naissancee">Date de naissance</label>
                         <div class="input-group date">

                                        <input type="text" class="form-control" id="date_naissance" name="date_naissance">
                                        <span class="input-group-text input-group-append input-group-addon" id="spanEstPaymentDate">
                                            <i class="simple-icon-calendar"></i>
                                        </span> 
                                    </div>
                             </div>
                       <div class="form-group col-md-6">
                          <label for="casting_lieu_naissance">Lieu de naissance</label>
                          <input type="text" class="form-control" id="lieu_naissance" name="lien_naissance" placeholder="Lieu de naissance">
                       </div>
                     </div>  
                      <div class="form-group col-md-6 js-guarantor-container" hidden>
                    <label for="guarantor">Nom et prénom du représentatnt légal </label>
                    <input type="text" class="form-control" id="nom_prenom" name="nom_prenom" placeholder="Représentant">
                </div>
                <div class="form-group col-md-6 js-guarantor_identification_number-container" hidden>
                    <label for="guarantor_identification_number">CIN du représentatnt légal</label>
                    <input type="number" class="form-control" id="cine" name="cine" placeholder="CINE">
                </div> 
                <div class="form-group col-md-6 js-guarantor_lien-container" hidden>
                    <label for="guarantor_identification_number">Lien</label>
                    <input type="text" class="form-control" id="lien_casting" name="lien_casting" placeholder="Lien">
                </div>      
                   
                
                    <div class="form-group" align="center">
                      <input type="hidden" name="action" id="action" />
                      <input type="hidden" name="hidden_id" id="hidden_id" />
                      <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="ADD" />
                    </div>
                    <div class=" col-md-6">
                      <span id="form_result"></span>
                    </div>
                 </form>

我设法将数据插入到单个表中,但我发现这个级别的复杂性:

在我的表格中插入时,当我从出生日期计算年龄并且发现年龄小于 18 岁时,我必须在铸件表中插入代表的 id 并插入表中代表信息名称,代表电影和链接,同时代表。

有可能做到吗?如果您有任何可以帮助我的想法,我将不胜感激。

更新

我在控制器中做了以下代码:

 public function store(Request $request)



      $representants = new Representant();
      $castings = new Casting();
  
      $date = $request['date_naissance']; // 24/8/1995
      $age = Carbon::now()->format('Y')- Carbon::createFromFormat('dd/mm/YYYY', $date)->format('Y');

      if ($age < 18) 

             $representants->nom_prenom = $request['nom_prenom'];
             $representants->cine = $request['cine'];
             $representants->lien_casting = $request['lien_casting'];
          // assign your data to the models needed
             $representants->save();
             $castings->nom = $request['nom'];
             $castings->prenom = $request['prenom'];
             $castings->cine = $request['cine'];
             $castings->date_naissance = $request['date_naissance'];
             $castings->lieu_naissance = $request['lieu_naissance'];
           //  $representant->lien_casting = $request['lien_casting'];
             $castings->representant_id = $representants->representant_id;
             $castings->save();
  else
     
             $castings->nom = $request['nom'];
             $castings->prenom = $request['prenom'];
             $castings->cine = $request['cine'];
             $castings->date_naissance = $request['date_naissance'];
             $castings->lieu_naissance = $request['lieu_naissance'];

  

但我收到以下错误:

message: "Unexpected data found. ↵Data missing",…
exception: "Carbon\\Exceptions\\InvalidFormatException"
file: "D:\\Projet_Cast_Infl\\vendor\\nesbot\\carbon\\src\\Carbon\\Traits\\Creator.php"
line: 643
message: "Unexpected data found.\r\nData missing"
trace: [file: "D:\Projet_Cast_Infl\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php", line: 665,…,…]

【问题讨论】:

【参考方案1】:

我想你可以! :) 但是你想要的大部分应该在控制器中完成。

yourController.php(您要发布到的控制器)

public function store(Request $request) 
  $representant = new Representant();
  $castings = new Casting();
  
  $date = $request['casting_date_naissance'] // 24/8/1995
  $age = Carbon::now()->format('Y') - Carbon::createFromFormat('d/m/Y', $date)->format('Y');

  if ($age < 18) 
  $representant->nom = $casting->nom = $request['casting_name'];
  // assign your data to the models needed

  $representant->save();
  $casting->representant_id = $representant->id;
  $casting->save()
  
  

【讨论】:

感谢您的帮助,请查看 mu 更新 Carbon::createFromFormat('d/m/Y') 尝试将您的d/m/Y 更改为您的日期输入方式,例外是输入日期和日期格式之间存在差异。

以上是关于如何使用 laravel 8 同时保存一对多关系数据的主要内容,如果未能解决你的问题,请参考以下文章

Laravel - 一对多关系上的保存方法的对立面是啥?

Laravel 不保存一对多关系

Laravel Eloquent - 保存/更新相关的一对多关系数据

使用 laravel,我如何创建一个将更新一对多关系的视图?

如何在 Laravel 中从多对多关系的一对多关系中获取项目?

Laravel SUM 一对多(逆)/属于关系