【问题标题】: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 获取所有类别的所有产品的计数(即多对多表上的所有记录)
【发布时间】:2020-03-16 04:05:00
【问题描述】:

我想要做的是从多对多表中计算记录数。我可以通过一个简单的查询来完成,但我想使用 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 表的所有记录的数量。我该怎么做?

【问题讨论】:

  • 那么如果我理解正确的话,你想知道一个类别中所有产品的数量吗?
  • 没有。我想获得所有类别的所有产品。不仅是一个类别中的所有产品。我知道如何得到这个。

标签: php laravel eloquent


【解决方案1】:

如果我的理解正确,您需要一种方法来返回 product_category 表中所有记录的数量。如果是这样的话,那就去吧:

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

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

【讨论】:

  • 没错。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 2019-09-03
  • 2017-04-01
相关资源
最近更新 更多