当前位置:首页 > CMS教程 > 其它CMS > 列表

Laravel 关联模型-关联新增和关联更新的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-12-29 16:42:22 浏览: 评论:0 

网上找了 Laravel 相关的关联新增和关联更新文档,写的都不是很满意,(基本都在抄文档)下面整理下自己代码中的关联操作方法

按照 Laravel 文档中的说明设置关联模型 参考地址

  1. //病人模型 
  2. class Patient extends Model 
  3. { 
  4.   /** 
  5.    * 病人附表 
  6.    * @return \Illuminate\Database\Eloquent\Relations\HasOne 
  7.    */ 
  8.   public function patientdata () 
  9.   { 
  10.     return $this->hasOne(PatientData::class); 
  11.   } 
  12.     
  13.  //病人附表模型 
  14. class PatientData extends Model 
  15. { 
  16.   public function patient() 
  17.   { 
  18.     return $this->belongsTo(Patient::class); 
  19.   }  

关联更新代码

  1. /** 
  2.  * 新增病人信息 
  3.  * @param array $data 
  4.  * 
  5.  * @return bool 
  6.  */ 
  7. public function savePatient($data=[]) 
  8. { 
  9.   DB::beginTransaction(); 
  10.   if($patient = $this->create($data)){ 
  11.     if ($res = $patient->patientdata()->create(["数据"])){ 
  12.       DB::commit(); 
  13.     } else{ 
  14.       DB::rollBack(); 
  15.     } 
  16.     return true; 
  17.   } 
  18.   return false; 
  19. } 

关联更新代码

  1. public function updatePatient($data=[]) 
  2. { 
  3.   DB::beginTransaction(); 
  4.   //先通过主键获得病人模型的实例 
  5.   $patient = $this->find($data['id']); 
  6.   if($patient->update($data)){ 
  7.     if ($res = $patient->patientdata()->where('patient_id',$data['id'])->update(["数据"])){ 
  8.       DB::commit(); 
  9.     } else{ 
  10.       DB::rollBack(); 
  11.     } 
  12.     return true; 
  13.   } 
  14.   return false; 
  15. }

Tags: Laravel关联模型 Laravel关联更新

分享到: