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 |
|---------------------|------------------|-------------------|
我假设您已经定义了模型关系
//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