我正在尝试使用嵌套循环来获取子类别,但我以错误结束 "Property [Category] does not exist on this collection instance"

i am trying to use nested loop to get the subcategory but i am ending in a error "Property [Category] does not exist on this collection instance"

我已经在我的类别模型中定义了自我关系

 public function Category()
        {
            return $this->hasmany(Category::class);
        }

在我的迁移中我定义了

 public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->String('Parent_id');
            $table->String('name');
            $table->String('status')->nullable();
            $table->timestamps();
        });
    }

在我的控制器中,我试图将类别的值设为

 return view('index')->with('cate',Category::all());

我正在尝试应用嵌套循环来通过我的 blade 文件中的子类别,如

 <div class="list-group list-group-collapse list-group-sm list-group-tree" id="list-group-men" data-children=".sub-men">
                           @foreach($cate as $cat) 
                            <div class="list-group-collapse sub-men">
                            <a class="list-group-item list-group-item-action" href="{{$cat->id}}" data-toggle="collapse" aria-expanded="true" aria-controls="{{$cat->id}}">{{$cat->name}}<small class="text-muted">(100)</small>
                            </a>
                            
                        <div class="collapse show" id="{{$cat->id}}" data-parent="#list-group-men">
                                    <div class="list-group">
                                      @foreach($cate->Category as $sub)
                                    <a href="#" class="list-group-item list-group-item-action active">{{$sub->name}} <small class="text-muted">(50)</small></a>
                                      @endforeach  
                                    </div>
                                </div>
                               
                            </div>
                            @endforeach
                            
                        </div>

我正在尝试应用嵌套循环,以便我可以看到 parent 类别的子类别,但我 运行 进入了错误

您的代码中有很多错误。

根据您的迁移,外键被命名为 Parent_id,因此鉴于此名称不遵循 laravel 约定,您需要在定义关系时指定确切的名称。此外,鉴于该关系可以 return 多个子项目,我建议您调整方法名称。

### Category.php

public function children()
{
    return $this->hasMany(Category::class, 'Parent_id');
}

因此,在查询数据时执行以下操作:

$categories = Category::with('children')->get();

return view('index')->with('categories', $categories);

另外:子类别想要访问其父类别,因此您可以在模型中定义另一个方法。

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

通过这种方式,您可以获得父类的信息:

$child = Category::find($id);
$parent = $child->parent;

我做错的是定义了一个自我关系,它应该被定义为

public function Category()
        {
            return $this->hasMany(self::class,'parent_id','id');
        }

为了获得父 ID,我必须使用

$category=Category::where('Parent_id','=','0')->get();
return view('index')->with('cate',$category);

而不是

return view('index')->with('cate',Category::all();