Reputation: 117
My models relationship is oneToMany eg: 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....
Upvotes: 5
Views: 5507
Reputation: 598
Did you set constraints in migration? Just write into Sample table migration row:
$table->foreign('patient_id')
->references('id')
->on('patients')
->onDelete('cascade');
For more info: Docs
Upvotes: 2
Reputation: 1553
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.
Upvotes: 4