【问题标题】:Trying to get property 'name' of non-object error in laravel eloquent试图在 laravel eloquent 中获取非对象错误的属性“名称”
【发布时间】:2021-07-18 13:39:36
【问题描述】:

category模型中自行加入Eloquent

public function parent()
{
   return $this->belongsTo(Category::class, 'parent_id');
 }

在刀片文件中:

@foreach($categories as $category)
    <tr>
        <td>{{ $category->parent }}</td> // error in this line
    </tr>
@endforeach

当我这样做时,它显示:

{
    "id": 1,
    "name": "mobile",
    "description": null,
    "image": null,
    "parent_id": 0,
    "created_at": null,
    "updated_at": null
}

当我将&lt;td&gt;{{ $category-&gt;parent }}&lt;/td&gt; 更改为&lt;td&gt;{{ $category-&gt;parent-&gt;name }}&lt;/td&gt; 时,它显示如下错误:

试图获取非对象的属性“名称”(查看:C:\Users\HP\Desktop\laravel-project\laravel_ecommerce\resources\views\admin\pages\category\index.blade.php)

如何访问$category-&gt;parent-&gt;name

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果父母没有孩子,那么你会得到这个错误。如果父对象为空,下面的示例将抛出 No Child 作为输出:

    {{ $category->parent->name ??  'No Child' }}
    

    【讨论】:

      【解决方案2】:

      其实你得到这个是因为 hasMany 这样的关系关系。

      {{$category->parent?$category->parent->name:"Some other message"}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-05
        • 2019-12-13
        • 2014-05-05
        • 2021-06-04
        • 1970-01-01
        • 2016-06-13
        • 2018-06-02
        • 2017-08-20
        相关资源
        最近更新 更多