Laravel 5中相关产品类别的产品清单

时间:2019-07-15 13:29:51

标签: php sql laravel-5 eloquent

我想在laravel 5中提供一个产品类别列表,以及与它们相关的产品数量(类别),如下所示:

电子产品(20)个项目,
手机(100个)

期望的JSON格式:

{
"name": "electronic",
"quantity": "20"
},
{
"name": "cell phones",
"quantity": "100"
},

有人知道如何在laravel 5中实现这一点吗?

编辑 现在,我的 controller 是这样的:

    private $categories;

public function __construct(Categories $categories) {
    $this->categories = $categories;
}

public function index(){

    $categories = $this->categories
    ->withCount('products')
    ->get();

    $data = ['data' => $categories];
    return response()->json($data);
}

在亩模型中,我有:

public function products()
{
    return $this->hasMany('App\Models\Products')
    ->selectRaw('category_id, count(*) as total')
    ->groupBy('category_id');
}

public function categories()
{
    return $this->hasOne('App\Models\Categories');
}

现在返回这些错误:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.categories_id' in 'where clause' (SQL: select `categories`.*, (select count(*) from `products` where `categories`.`id` = `products`.`categories_id`) as `products_count` from `categories`)"

在我的数据库image of the column

laravel将我的列称为复数形式,当我将数据库中的列名称更改为 categories_id 时,它工作正常,但我不知道该怎么做

1 个答案:

答案 0 :(得分:0)

我已经通过在模型中指定外键category_id来解决了这个问题,类别模型中的最终代码是:

public function products()
{
    return $this->hasMany('App\Models\Products', 'category_id')
    ->selectRaw('category_id, count(*) as total')
    ->groupBy('category_id');
}

效果很好

POSTMAN的JSON响应是:

        "id": 18,
        "category_name": "electronics",
        "description": null,
        "icon": "tv",
        "created_at": null,
        "updated_at": null,
        "products_count": 20
    }

如果遇到相同的问题,请参见that link too