【问题标题】:Laravel cannot retrieve data using one to many not workingLaravel 无法使用一对多无法检索数据
【发布时间】: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


【解决方案1】:

在关系的belongsTo 侧,当未指定外键名称时,使用关系的名称构建。在这种情况下,由于您的关系名为 cities,Laravel 将查找字段 doctors.cities_id

如果您的外键不是cities_id,那么您需要更改关系方法的名称,或者指定外键的名称:

public function cities() {
    return $this->belongsTo('App\City', 'city_id');
}

// or, better:

public function city() {
    return $this->belongsTo('App\City');
}

另外,正如@Christophvh 所提到的,你的关系的命名有点不对劲,但在程序上并不是不正确的。当belongsTo/hasOne 关系被命名为单数,belongsToMany/hasMany 关系被命名为复数时,它更有意义,更易读。

【讨论】:

    【解决方案2】:

    您正在尝试循环一个集合而不是一个数组。

    2 个解决方案:

    1) 添加->获取();当您在控制器中调用您的关系时

    2)
    使用

     @foreach($doctors->all() as $doctor)
    

    而不是

    @foreach($doctors as $doctor)
    

    还有一个快速提示: 您的命名并不能真正说明您在做什么。你应该像下面这样交换它们。 '一个医生属于一个城市' & '一个城市有很多医生'

    Doctor.php

    public function city()
    {
        return $this->belongsTo('App\City');
    }
    

    City.php

    public function doctors()
    {
        return $this->hasMany('App\Doctor');
    }
    

    【讨论】:

    • 第一部分不正确。你可以使用 foreach 循环 Laravel Collection。 Laravel 的Collection 实现了IteratorAggregate 接口,它扩展了Traversable 接口,允许在foreach 中使用。
    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 2013-09-14
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多