我试图建立两个模型之间的关系,称为病房和床。病房的表结构为
<>之前Id | ward_naem| ward_type1 | ENT |男2 |心|男之前床的桌子是
<>之前Id | ward_name| ward_id1 | 3 | 12 | 3 | 12 | 2 | 2之前床模型中的关系
public function wards()
{
return $this->belongsTo('Wards');
}
Relations is Wards model is
public function beds()
{
return $this->hasMany('Beds');
}
在我的控制器我写这些行
public function index()
{
$beds = Beds::all();
return IlluminateSupportFacadesView::make('adminipd.index',compact('beds'));
}
,当它重定向到索引与对象命名为beds
我检索ward_name
与$beds
的对象作为
<td>{{{ $bed->wards()->ward_name}}}</td>
<td>{{{ $bed->bed_no }}}</td>
它不起作用,如果我删除这行
它会给出一个空白页 <td>{{{ $bed->wards()->ward_name}}}</td>
对于"bed_no"可以正常工作。在我的laravel项目的日志文件中,我得到了一个错误
ERROR: exception 'ErrorException' with message 'Undefined property: IlluminateDatabaseEloquentRelationsBelongsTo::$ward_name'
错误是因为您正在使用wards()
,括号将返回您的关系而不是数据本身。使用ward
代替,不带括号。
并且在您的wards
表中您有一个错别字。ward_naem
应为ward_name
然后将Bed
模型更改为
public function ward() // changed from wards to ward
{
return $this->belongsTo('Wards');
}
或
public function wards()
{
return $this->belongsTo('Wards', 'ward_id'); // added the key
}
那么你可以得到所有的床位与病房如下。这不是必需的,但对性能有好处。
$beds = Beds::with('ward')->get();
那么您可以像下面这样访问床名。
{{ $bed->ward->ward_name }}
从
更改代码 <td>{{{ $bed->wards()->ward_name}}}</td>
<td>{{{ $bed->wards->ward_name}}}</td>
实际上,您应该将wards()方法重命名为ward(),因为您得到的是一个实例而不是实例,因为它属于关系。