简体   繁体   English

如何使用 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

This what i want to do is to take the count of records from many-to-many table.我想要做的是从多对多表中获取记录数。 I can do it with a simple query, but I want to use the ORM of Laravel 5.2.我可以通过一个简单的查询来完成,但我想使用 Laravel 5.2 的 ORM。 These are my models:这些是我的模型:

Category model品类模型

class Category extends BaseModel {
    protected $table = 'categories';

    public function products() {
        return $this->belongsToMany('App\Models\Product', 'product_category');
    }

Product model产品型号

class Product extends BaseModel {
    protected $table = 'products';

    public function categories() {
        return $this->belongsToMany('App\Models\Category', 'product_category')->withTimestamps();
    }

I want to add a method in the Category model or using the Laravel ORM to take the number of all products for all categories ie the number of all records from the product_category table.我想在 Category 模型中添加一个方法或使用 Laravel ORM 来获取所有类别的所有产品的数量,即product_category表中的所有记录的数量。 How can I do it ?我该怎么做?

If I am understanding you right, you want a method that will return the number of all records in the product_category table.如果我理解正确,您需要一种方法来返回product_category表中所有记录的数量。 If that is the case, here you go:如果是这种情况,请执行以下操作:

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

You may find more info about this here: https://laravel.com/docs/5.2/queries您可以在此处找到更多相关信息: https : //laravel.com/docs/5.2/queries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Yii:类别为MANY_MANY的产品可能具有父项,也可能没有父项。 获取所有产品 - Yii : Products with MANY_MANY categories and categories may or not has parent. Get all products 获取多对多多态中的所有关系 - Get all relationships in many-to-many polymorphic MYSQL / PHP加入多对多,获取所有类别的帖子 - MYSQL/PHP join many-to-many, fetch posts with their all categories Laravel:在A与B之间的多对多关系中,如何从多个A中获得所有B? - Laravel : In a many-to-many relationship between A and B, how to get all B's from multiple A's? 显示子类别下的所有产品 - Laravel 5.2 - Display all products under sub-categories - Laravel 5.2 Laravel更新多对多关系中的所有记录 - Laravel updating all records in many to many relationship 如何将多对多表中所有值的选择语句组合在一起 - How do I combine select statements for all values in a many-to-many table 教义:我如何让多对多关系的所有参与者 - Doctrine: How could I get all participants of many-to-many relationships JSON 对 Laravel 中多对多关系的所有列的响应 - JSON response with all columns for a many-to-many relation in Laravel 使用 eloquent 如何获取 pivot 表中最大值的多对多关系的所有记录 - Using eloquent how to get all records of a many to many relationship that the max value in their pivot table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM