Laravel 4 deleting multiple models related by fore

2019-09-01 02:11发布

问题:

So I have three models and when when one of them dAgency is deleted delete-() I'd like all three to be deleted. The problem is that two of them are being deleted, while the top parent one DemDataSet isn't being deleted. Additionally, when I call:

echo "<pre>", dd(dAgency::find(21)->DemographicReport()->DemDataSet()->get()), "</pre>";

I get this error: Call to undefined method Illuminate\Database\Query\Builder::DemDataSet() But when I try:

echo "<pre>", dd(dAgency::find(21)->DemographicReport()->get()), "</pre>";

It works. So I know the problem is my relation between my DemDataSet model. Below is my model:

<?php

class DemDataSet extends Eloquent {

    public $timestamps = false;
    protected $connection = 'epcr_dem_data';
    protected $table = 'DEMDataSet';
    protected $primaryKey = 'pk_DEMDataSet';

    public function DemographicReport(){
        return $this->hasOne('DemographicReport','fk_DEMDataSet','pk_DEMDataSet');
    }


}

class DemographicReport extends Eloquent {

    public $timestamps = false;
    protected $connection = 'epcr_dem_data';
    protected $table = 'DemographicReport';
    protected $primaryKey = 'pk_DemographicReport';

    public function DemDataSet (){
        return $this->belongsTo('DemDataSet','fk_DEMDataSet','pk_DEMDataSet');
    }

    public function dAgency(){
        return $this->hasOne('dAgency','fk_DemographicReport','pk_DemographicReport');
    }

    public function delete(){
        parent::delete();
        return $this->DemDataSet()->delete();
    }

}

class dAgency extends Eloquent {

    public $timestamps = false;
    protected $connection = 'epcr_dem_data';
    protected $table = 'dAgency';
    protected $primaryKey = 'pk_dAgency';

    public function DemographicReport(){
        return $this->belongsTo('DemographicReport','fk_DemographicReport','pk_DemographicReport');
    }

    public function dAgency_10(){
        return $this->hasMany('dAgency_10','fk_dAgency','pk_dAgency');
    }

    public function delete(){
        parent::delete();
        return $this->DemographicReport->delete();
    }

}

?>

I've been wrestling with this one for two days now! I really appreciate you taking the time to look at this.

回答1:

The right way to query laravel model with relationship is this way:

//This is to pull all DemDataSet from DemographicReport
dAgency::find(21)->DemographicReport()->first()->DemDataSet;

//If you need further query, then you call DemDataSet as a method
dAgency::find(21)->DemographicReport()->first()->DemDataSet()->where('your condition here')->get();