php – Laravel 5.1删除关系
作者:互联网
我的模型关系是oneToMany例如:PatientToSample
Patient_Model:
class Patient_Model extends Model implements Jsonable{
use SoftDeletes;
protected $table = 'patients';
public function samples(){
return $this->hasMany('App\Models\Sample_Model','code','patient_id');
}
}
Sample_Model:
class Sample_Model extends Model{
use SoftDeletes;
protected $table = 'samples';
public function patient(){
return $this->belongsTo('App\Models\Patient_Model','patient_id','code');
}
}
我认为使用删除Patient和Sample的功能
public function delete(Request $request){
$patient = Patient_Model::withTrashed()
->where("id",$request->get("id"))
->delete();
return json_encode($patient);
}
但现在只删除病人….
解决方法:
这是一种方法.
public function delete(Request $request){
$patient = Patient_Model::withTrashed()
->find($request->get("id"));
$patient->samples()->delete();
$patient->delete();
return json_encode($patient);
}
还有一种方法可以将关系删除附加到父模型的删除事件,如here所述.
标签:php,laravel,relationships 来源: https://codeday.me/bug/20190609/1202950.html