如何使用laravel 5.2统计所有类别的所有产品(即多对多表上的所有记录)


How to get count for all products for all categories (i.e all records on many-to-many table) with laravel 5.2

我想做的是从多到多表中获取记录数。我可以用一个简单的查询来完成,但我想使用Laravel 5.2的ORM。这些是我的型号:

类别模型

class Category extends BaseModel {
    protected $table = 'categories';
    public function products() {
        return $this->belongsToMany('App'Models'Product', 'product_category');
    }

产品型号

class Product extends BaseModel {
    protected $table = 'products';
    public function categories() {
        return $this->belongsToMany('App'Models'Category', 'product_category')->withTimestamps();
    }

我想在Category模型中添加一个方法,或者使用Laravel ORM来获取所有类别的所有产品的数量,即product_category表中所有记录的数量。我该怎么做?

如果我理解得对,您需要一个返回product_category表中所有记录数的方法。如果是这样的话,给你:

public function numberOfProductCategories() {
    return DB::table('product_category')->count();
}

你可以在这里找到更多信息:https://laravel.com/docs/5.2/queries