【发布时间】:2016-04-11 14:18:06
【问题描述】:
我对 Laravel 中的一对多关系有疑问。我无法从数据库中检索我的数据。我的代码如下。
Doctor.php
public function cities()
{
return $this->belongsTo('App\City');
}
City.php
public function doctor()
{
return $this->hasMany('App\Doctor');
}
查看
@foreach($doctors as $doctor)
<tr>
<td data-title="ID">{{ $doctor->id }}</td>
<td data-title="Name">{{ $doctor->name }}</td>
<td data-title="Hospital">{{ $doctor->hospital }}</td>
<td data-title="Designation">{{ $doctor->designation }}</td>
<td data-title="City">{{ $doctor->cities->name }}</td> <!-- problem in this line -->
</tr>
@endforeach
当我尝试查看数据时显示错误:
3d7f581c490d492093e6e73f8ebd29525504e56b.php 第 46 行中的 ErrorException:
试图获取非对象的属性(视图:D:\xampp\htdocs\tourisms\root\resources\views\doctors\index.blade.php)
【问题讨论】:
-
您能否检查由
$queries = DB::getQueryLog(); $last_query = end($queries); echo $last_query;构造的查询并在phpmyadmin 中查看实际创建的查询? -
您有没有与城市无关的医生?
-
没有。所有医生都有城市。 @Laerte
-
@SulthanAllaudeen 我应该在哪里尝试这段代码?
-
在你的控制器中,即在你构造这个数组之后
doctors
标签: php laravel laravel-5 eloquent