[英]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.