我对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
对象的属性,但是我没有。请指导我解决此问题。
答案 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
}
因此您可以创建关系。
希望它对您有用