vendredi 5 mars 2021

Laravel many to many relationship with eager

I have the following tables:-

Table: facilities

Columns:

id bigint(20) UN AI PK 
name varchar(255) 


Table: reports

Columns:

id bigint(20) UN AI PK 
number varchar(20) 
visit_date date 
type varchar(255) 
user_id bigint(20) UN 

Table: observations

Columns:

id bigint(20) UN AI PK 
observation longtext 
recommendation longtext 
priority varchar(255) 
status bigint(20) UN 
report_facility_id bigint(20) UN

Table: report_facility

Columns:

id bigint(20) UN AI PK 
facility_id bigint(20) UN 
report_id bigint(20) UN

Models:-

class Facility extends Model
{
 
    public function reports()
    {
        return $this->belongsToMany('App\Report');
    }

   
}

class Report extends Model
{

    public function facilities()
    {
        return $this->belongsToMany('App\Facility','report_facility','report_id','facility_id');
    }
   
}

class ReportFacility extends Model
{

    public function observations()
    {
        return $this->hasMany('App\Observation');
    }

    public function visit_details()
    {
        return $this->hasMany('App\VisitDetail');
    }

    public function facility()
    {
        return $this->belongsTo('App\Facility');
        
    }

    public function report()
    {
        return $this->belongsTo('App\Report');
    }
}

The relationship is Each (Report) has one or many (Facility) and each (Facility) have one or many (Observation).

This is what i am using right now

Report::where('number',$number)->first()
        ->load(['facilities' => function($q) {
            $q->with('observations');
        }]);

The above is returning (Facility) with loading all the observations related to that facility , instead of loading only observations related to that report .

What is the proper eloquent query to be used to load all reports on DB with their facility and load observations related to each facility written for that report.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire