我试图从一个类别查询所有产品,它是子类别。 但我在我的控制器上出现这个错误。找不到类'App Http Controllers App Category'
Class 'App\Http\Controllers\App\Category' not found
我有一个产品表
id
name
category_id (fk)
而且一类表:
id
name
parent_id
因此,如果类别是这样的:
id | title | parent
1 | Electronics | null
2 | Smartphones | 1
3 | Android | 2
4 | Clothes | null
和产品:
id | title | category_id (fk)
1 | Smartphone1 | 3
1 | Smartphone2 | 2
这是我对如何做到这一点的代码:
类型模型 - 应用程序/ category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class category extends Model
{
//
protected $fillable = array('id', 'name', 'parent_id', 'image_url');
public function products()
{
// Build an array containing the parent category ID and all subcategory IDs found
$categoryIds = array_merge([$this->id], $this->subcategoryIds());
// Find all products that match the retrieved category IDs
return Product::whereIn('category_id', $categoryIds)->get();
}
protected function subcategoryIds($id = null, &$ids= [])
{
// If no ID is passed, set the current model ID as the parent
if (is_null($id)) {
$id = $this->id;
}
// Find subcategory IDs
$categoryIds = $this->query()->where('parent', $id)->lists('id');
// Add each ID to the list and recursively find other subcategory IDs
foreach ($categoryIds as $categoryId) {
$ids[] = $categoryId;
$ids += $this->subcategoryIds($categoryId, $ids);
}
return $ids;
}
}
而且我的应用程序/ HTTP /控制器/ ProductController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Product;
use App\Category;
use App\Repositories\CategoryRepository;
public function getProductsFromCategory()
{
$id = 1;
$products = App\Category::find($id)->products();
return view('welcome', [
'products' => $products,
]);
}
如果包含'Category',为什么不直接使用它:'$ products = Category :: find($ id) - > products();' –