繁体   English   中英

试图在 laravel eloquent 中获取非对象错误的属性“名称”

[英]Trying to get property 'name' of non-object error in laravel eloquent

自加入 Eloquent category Model

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
}

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

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

如何访问$category->parent->name

如果父母没有孩子,那么您将收到此错误。 如果父 object 为空,则以下示例将No Child作为 output 抛出:

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

其实你得到这个是因为有很多这样的关系。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM