Laravel 5.1 删除关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32961236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.1 Delete relationships
提问by u5066178
My models relationship is oneToMany eg: PatientToSample
我的模型关系是 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');
}
}
I think use the function delete Patient and Sample
我认为使用删除患者和样本的功能
public function delete(Request $request){
$patient = Patient_Model::withTrashed()
->where("id",$request->get("id"))
->delete();
return json_encode($patient);
}
But now only delete Patient....
但现在只能删除患者....
回答by show-me-the-code
This is one way to do it.
这是一种方法。
public function delete(Request $request){
$patient = Patient_Model::withTrashed()
->find($request->get("id"));
$patient->samples()->delete();
$patient->delete();
return json_encode($patient);
}
There is also a way to attach the relationship deletion to a delete event of the parent model, as discussed here.
还有一种方式的关系删除连接到父模型的删除事件,如讨论在这里。