试图获得非对象Laravel hasMany关系的属性

时间:2019-07-05 04:11:58

标签: laravel eloquent

我对laravel还是陌生的,而且我正在了解eloquent中的关系。我有3个模型

Report
ReportModule
ReportSubModule

这种关系

SubModule hasMany Module
Report hasMany ReportModule
Report hasMany ReportSubModule

当我尝试从视图中的ReportSubModule对象获取Report时,我没有错误,但是当我尝试从视图中的ReportModule对象获取Report时我收到错误Trying to get property of non-object。如果我打印ReportModule对象,我会看到json,我认为我正在获取对象,但无法获取其属性

这是我的代码

报告(型号) 命名空间应用;

use Illuminate\Database\Eloquent\Model;

class Report extends Model
{
    public function report_module(){
        //module_id is column in reports table that corresponds to 
        //id column in report_modules table
        return $this->belongsTo(ReportModule::class,'module_id');
    }


    public function sub_module(){
        //sub_module_id is column in reports table that corresponds to 
        //id column in report_modules table
        return $this->belongsTo(ReportSubModule::class,'sub_module_id');
    }


}

ReportModule(模型)

namespace App;

use Illuminate\Database\Eloquent\Model;

class ReportModule extends Model
{
    public function subModules(){
        return $this->hasMany(ReportSubModule::class);
    }

    public function reports(){
        return $this->hasMany(Report::class);
    }
}

ReportSubModule(模型)

namespace App;

use Illuminate\Database\Eloquent\Model;

class ReportSubModule extends Model
{
    public function module(){
        return $this->belongsTo(ReportModule::class);
    }
    public function reports(){
        return $this->hasMany(Report::class);
    }
}

视图

<a href="{{route('reports.edit',$report->id)}}"><h4> {{$report ->report_name}} </h4></a>
            <small>{{ $report->sub_module->sub_module_name }} </small><br/><br/>
            <?php
                $m = $report->report_module;
                <!-- i get error on below line -->
                 echo $m->module_name;
            ?>

我在这里做错了什么。我应该能够像ReportModule那样获得ReportSubModule对象的属性,但是我没有。请指导我解决此问题。

1 个答案:

答案 0 :(得分:1)

I assume you have the relationship like this - 

Report id(primary key) -> ReportModule report_id(foreign key)
ReportModule id(primary key) -> ReportSubModule report_module_id(foreign key)

You will have the relation ship in each Model like below -

1) Report Model - 
public function reportModule(){
 return $this->hasMany(ReportModule::class,'report_id'); //you can use has one as well if required
}

2) Report Model - 
//relationship with report table
public function module(){
 return $this->belongsTo(Report::class,'report_id');
}

//relationship with report sub module
public function reportSubModule(){
 return $this->hasMany(ReportSubModule::class,'report_module_id); // you can use has one if required
}

因此您可以创建关系。

希望它对您有用