Getting count from pivot table in laravel eloquent(从 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
以上查询结果如下:-
id description count(products.id)
1 Shoes 3
2 Bag 2
3 Sun glasses 2
4 Shirt 2
如何使用 laravel eloquent 完成此任务(不使用查询构建器)????我如何使用 laravel eloquent 获取每个产品的订购次数??
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??
推荐答案
注意 Eloquent
在底层使用 QueryBuilder
,所以在 Laravel 中没有这样的东西,例如不使用查询生成器的查询雄辩".
Mind that Eloquent
uses QueryBuilder
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
阅读更多关于 Eloquent 访问器和突变体,
关于动态属性,上面的访问器模仿的行为.
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 eloquent 中的数据透视表中获取计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 laravel eloquent 中的数据透视表中获取计数
基础教程推荐
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01