5

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....

麦志坤
  • 117
  • 1
  • 9
  • Check out this: http://stackoverflow.com/a/15019260/2772319 – Emeka Mbah Oct 06 '15 at 05:01
  • 1
    possible duplicate of [Automatically deleting related rows in Laravel (Eloquent ORM)](http://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm) – Emeka Mbah Oct 06 '15 at 05:06

2 Answers2

4

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.

show-me-the-code
  • 1,553
  • 1
  • 12
  • 14
  • This is not what OP is looking for. You are doing this inside a controller. OP wants the related rows to be deleted automatically without the need for the answer you gave. – Emeka Mbah Oct 06 '15 at 05:20
  • I may have misunderstood the question, but that is a simple modification to the exact code OP posted, and looks to me like he is trying to delete relationship when the parent model is deleted as mentioned in these lines: "I think use the function delete Patient and Sample".. " But now only delete Patient....". – show-me-the-code Oct 06 '15 at 05:25
2

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

Dmytrechko
  • 598
  • 3
  • 11