【问题标题】:Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$center_name未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$center_name
【发布时间】:2018-11-22 15:02:43
【问题描述】:

您好,以下是我的关系

SchoolsList.php

public function requisitions()
{
    return $this->hasMany(Requisition::class);
}

申请.php

public function schools()
{
    return $this->belongsTo(SchoolsList::class);
}

我的刀

<td>{{ dd($requisition->schools()->center_name) }}</td>

我收到此错误。

未定义的属性: Illuminate\Database\Eloquent\Relations\BelongsTo::$center_name

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果你想优化这个并且不遇到数据表问题,例如,这样做:

    <td>{{ ($requisition->schools) ? $requisition->schools->center_name : "" }}</td>
    

    【讨论】:

      【解决方案2】:

      你只需要这样做:

      $requisition->schools()->first()->center_name

      这将为您提供申请所属学校的 center_name。

      【讨论】:

        【解决方案3】:

        $requisition->schools() 它是Illuminate\Database\Eloquent\Relations\BelongsTo 的实例,但$requisition->schools 是Illuminate\Database\Eloquent\Collection 的实例。

        @if ($requisition->schools) // or $requisition->school
           <td>{{ $requisition->schools->center_name }}</td>
           // or <td>{{ $requisition->school->center_name }}</td> // corrected relation
        @endif
        

        如果你的关系是属于的,建议使用single关系名称

        public function school()
        {
            return $this->belongsTo(SchoolsList::class);
        }
        

        【讨论】:

          【解决方案4】:

          试试这个:
          &lt;td&gt;{{ dd($requisition-&gt;schools-&gt;center_name) }}&lt;/td&gt;

          如果您收到此错误:Trying to get property of non-object 问题出在您的关系中,请检查数据库列名,数据库的列名必须:

          对于schools table:您应该在表requisitions 中有requisition_id
          在这里检查 laravel 关系约定

          https://laravel.com/docs/5.6/eloquent-relationships#one-to-many

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-11-23
            • 2020-01-26
            • 2018-11-19
            • 2020-07-08
            • 2020-05-04
            • 2021-03-12
            • 2021-09-23
            • 2020-01-29
            相关资源
            最近更新 更多