Laravel 与渴望的多对多关系

Posted

技术标签:

【中文标题】Laravel 与渴望的多对多关系【英文标题】:Laravel many to many relationship with eager 【发布时间】:2021-06-04 07:00:25 【问题描述】:

我有以下表格:-

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

型号:-

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');
    

关系是每个(报告)有一个或多个(设施),每个(设施)有一个或多个(观察)。

这是我现在使用的

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

以上返回 (Facility) 并加载与该设施相关的所有观察结果,而不是仅加载与该报告相关的观察结果。

什么是正确的 eloquent 查询,用于将所有报告及其设施加载到 DB 上,并加载与为该报告编写的每个设施相关的观察结果。

【问题讨论】:

【参考方案1】:

通过在 ReportFacility Model 中添加以下行来解决:-

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

并将雄辩的查询更改为:-

Report::where('number',$number)->first()
        ->load('report_facilities.observations');

【讨论】:

【参考方案2】:

load()方法调用中分离关系。

Report::where('number',$number)->first()
        ->load('facilities', 'observations');

【讨论】:

调用模型 [App\Report] 上的未定义关系 [observations]。 我认为当我按照你的解释分离关系时,观察结果将直接加载到报告下,我希望它作为数组加载,每个设施都有观察数组​​ 抱歉,我没有看到报告模型上没有定义观察结果。 尝试点符号,如->load('facilities.observations') 我试过了,它返回相同,它返回所有报告中与该设施相关的所有观察结果

以上是关于Laravel 与渴望的多对多关系的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 与 uuid 的多对多关系返回总是空的

Laravel Datatable 与多个表的多对多关系

与多个中间表的多对多 Laravel Eloquent 关系

Laravel 8:在空的多对多关系中使用枢轴时出错

Laravel - 渴望加载多对多,仅获取一条记录(不是集合)

Laravel 上的多对多问题关系