2016-02-20 57 views
0

我试图从一个类别查询所有产品,它是子类别。 但我在我的控制器上出现这个错误。找不到类'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, 
      ]); 

     } 
+0

如果包含'Category',为什么不直接使用它:'$ products = Category :: find($ id) - > products();' –

回答

3

更换

$products = App\Category::find($id)->products();

$products = Category::find($id)->products();

你已经导入了类,并没有重新指定路径。

0

你用'category'声明类,并用它与资本符号App \ Category一起使用,将类名改为class类。 如果你使用顶层而不是每次你可以直接使用Category :: whatever(),你都不必使用App \ Cateogry进行调用。

相关问题