从laravel雄辩的数据透视表中计数 [英] Getting count from pivot table in laravel eloquent
问题描述
我有很多关系的订单和产品。
I have a many to many relationship for orders and products.
<?php
class Order extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
public function products()
{
return $this->belongsToMany('Product');
}
}
?>
<?php
class Product extends Eloquent {
public function orders()
{
return $this->belongsToMany('Order');
}
}
?>
需要获取每个产品订购的次数。在mysql中,此任务可以通过使用以下查询
Need to fetch the number of times each product is ordered.In mysql,this task can be achieved by using the following query
SELECT products.id, products.description, count( products.id )
FROM products
INNER JOIN order_product ON products.id = order_product.product_id
INNER JOIN orders ON orders.id = order_product.order_id
GROUP BY product_id
LIMIT 0 , 30
上述查询的结果如下: -
Result of the above query is as follows:-
id description count(products.id)
1 Shoes 3
2 Bag 2
3 Sun glasses 2
4 Shirt 2
如何使用laravel雄辩(无需使用查询构建器)实现此任务????我如何获取次数每个产品都是使用laravel雄辩命令的?
How this task can be achieved using laravel eloquent (without using query builder)????How can i fetch the number of times each product is ordered using laravel eloquent??
推荐答案
注意口述
使用 Query\Builder
在引擎盖下,所以在Laravel中没有这样的东西,像查询雄辩而不使用查询构建器。
Mind that Eloquent
uses Query\Builder
under the hood, so there is no such thing in Laravel, like 'query eloquent without using query builder'.
这就是你需要的:
// additional helper relation for the count
public function ordersCount()
{
return $this->belongsToMany('Order')
->selectRaw('count(orders.id) as aggregate')
->groupBy('pivot_product_id');
}
// accessor for easier fetching the count
public function getOrdersCountAttribute()
{
if ( ! array_key_exists('ordersCount', $this->relations)) $this->load('ordersCount');
$related = $this->getRelation('ordersCount')->first();
return ($related) ? $related->aggregate : 0;
}
这将让您利用热切的加载:
This will let you take advantage of eager loading:
$products = Product::with('ordersCount')->get();
// then for each product you can call it like this
$products->first()->ordersCount; // thanks to the accessor
详细了解雄辩的访问者& mutators ,
以及动态属性,上述访问者模拟的行为。
and about dynamic properties, of which behaviour the above accessor mimics.
当然可以使用简单的连接来获取完全相同的查询就像你的例子。
Of course you could use simple joins to get exactly the same query like in you example.
这篇关于从laravel雄辩的数据透视表中计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!