错误:异常"错误异常",消息为"未定义的属性:照明\数据库\雄辩\关系\属于:$ward_name"



我试图建立两个模型之间的关系,称为病房和床。病房的表结构为

<>之前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(),因为您得到的是一个实例而不是实例,因为它属于关系。

相关内容

最新更新