dqy13020940 2016-02-20 22:09
浏览 89
已采纳

找不到类'App \ Http \ Controllers \ App \ Category'

I'm trying to query all products from a category and it's subcategories. But I'm getting this error on my Controller.

Class 'App\Http\Controllers\App\Category' not found

I have a products table

id
name
category_id (fk)

And a categories table:

id
name
parent_id

So if the categories looked like this:

id | title | parent
1  | Electronics | null
2  | Smartphones | 1
3  | Android   | 2
4  | Clothes   | null

And products:

id | title | category_id (fk)
1  | Smartphone1 | 3
1  | Smartphone2 | 2

This is my code on how to do this:

The Category Model - 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;
    }
}

And on my 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,
            ]);

        }
  • 写回答

2条回答 默认 最新

  • dreamevil0002 2016-02-20 22:14
    关注

    Replace

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

    with

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

    You've already imported the class and don't have to specify the path again.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探