Laravel无法获得类别的父项

问题描述 投票:0回答:2

我正在尝试创建类别,我想显示类别名称及其父类别,但我不断收到此错误消息:

试图获取非对象的属性“名称”。

这是我的模特:

public $timestamps = false;
public $primaryKey = 'id';
public function categories(){
    return $this->hasMany(category::class);
}

public function childrenCategories(){
    return $this->hasMany(Category::class)->with('categories');
}

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

这是我的观点:

@foreach($categories as $category )
    <tr>
        <td>{{$category->id}}</td>
        <td>{{$category->name}}</td>
        <td>{{$category->parent->name}}</td>
    </tr>
@endforeach
php laravel
2个回答
0
投票

问题出在父类别中,类别ID为null的类别中>]

@foreach($categories as $category )
    <tr>
        <td>{{$category->id}}</td>
        <td>{{$category->name}}</td>
        <td>{{$category->parent != null ? $category->parent->name : ''}}</td>
    </tr>
@endforeach

-1
投票

您可以使用

© www.soinside.com 2019 - 2024. All rights reserved.