【问题标题】:Class 'App\Http\Controllers\App\Category' not found找不到类“App\Http\Controllers\App\Category”
【发布时间】:2016-06-02 11:10:47
【问题描述】:

我正在尝试从一个类别及其子类别中查询所有产品。 但是我的控制器上出现了这个错误。

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

这是我的代码:

类别模型 - app/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;
    }
}

在我的 app/Http/Controllers/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)-&gt;products();

标签: php mysql laravel laravel-5


【解决方案1】:

替换

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

$products = Category::find($id)-&gt;products();

您已经导入了类,无需再次指定路径。

【讨论】:

    【解决方案2】:

    您使用“类别”声明类并使用大写符号 App\Category 使用它,因此将您的类名称更改为类类别。 如果您在顶部使用,则不必每次都使用 App\Cateogry 调用,您可以直接使用 Category::whatever()。

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2020-02-02
      • 2016-05-15
      • 2018-05-02
      • 2017-07-12
      • 2019-04-14
      • 2015-12-18
      • 2017-11-29
      • 2017-08-10
      相关资源
      最近更新 更多