Laravel 5.1 Delete Relationships

My attitude towards models is equal to oneToMany, for example: 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 delete patient and Sample function

public function delete(Request $request){
    $patient = Patient_Model::withTrashed()
        ->where("id",$request->get("id"))
        ->delete();

    return json_encode($patient);
}

But now only remove the patient ...

+4
source share
2 answers

This is one way to do this.

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 associate a relationship deletion with a parent model deletion event, as discussed here .

+4
source

Have migration restrictions been established? Just write in the migration line of the Sample table:

$table->foreign('patient_id')
      ->references('id')
      ->on('patients')
      ->onDelete('cascade');  

For more information: Docs

+1
source

Source: https://habr.com/ru/post/1610346/


All Articles