all()函数中的每个Laravel都没有数据

问题描述 投票:1回答:1

foreach和print函数后,laravel中没有数据打印或all()函数产品负责人

use App\ProductsCategory;
use App\ProductsSubCategory;
  public function create()
{
    $categories = ProductsCategory::all();
    $subcategories = ProductsSubCategory::all();
    return view('admin.product.create', compact('categories','subcategories'));
}

Create.blade

@foreach($categories as $category)
{{ $category->category_name }} // no data printed
            @foreach($subcategories as $subcategory)
                @if($subcategory->parent_category_id == $category->id)
                    {{ $subcategory->subcategory_name }}  // no data printed
                @endif
            @endforeach
@endforeach

产品类别表

|---------------------|------------------|
|      id             |    category_name |
|---------------------|------------------|
|          1          |    Category 1    |
|---------------------|------------------|
|          2          |    Category 2    |
|---------------------|------------------|

产品子类别表

|---------------------|------------------|-------------------|
|      id             | subcategory_name |parent_category_id | 
|---------------------|------------------|-------------------|
|          1          |  Subcategory 1   |     1             |
|---------------------|------------------|-------------------|
|          2          |   Subcategory 2  |     1             |
|---------------------|------------------|-------------------|
php laravel eloquent
1个回答
0
投票

我假设您已经定义了模型关系

//App\ProductsCategory
public function subCategories() {
  return $this->hasMany('App\ProductsSubCategory', 'parent_category_id', 'id');
}

//App\ProductsSubCategory
public function parentCategory() {
  return $this->belongsTo('App\ProductsCategory', 'parent_category_id');
}

//Controller
//...
public function create()
{
    //use [eager loading][1] 
    $categoriesWithSubCategories = ProductsCategory::with('subCategories')->get();
    return view('admin.product.create', compact('categoriesWithSubCategories'));
}

//Create.blade.php
@forelse($categoriesWithSubCategories as $category)
     {{ $category->category_name }}
     @forelse($category->subCategories as $subcategory)    
         {{ $subcategory->subcategory_name }}
     @empty
     <p>No sub categories found</p>      
     @endforelse
@empty
<p>No categories found</p>
@endforelse
© www.soinside.com 2019 - 2024. All rights reserved.