从数据透视表中获取laravel雄辩数
我有一个订单和产品多对多的关系。从数据透视表中获取laravel雄辩数
<?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');
}
}
?>
需要获取的倍每一产品ordered.In的MySQL,该任务可以通过使用以下查询上述查询的
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雄辩(不使用查询生成器)来实现此任务????如何获取每个产品使用laravel雄辩的次数?
请注意,Eloquent
在底层使用了Query\Builder
,所以在Laravel中没有这样的事情,比如“不使用查询构建器的查询雄辩”。
这就是你需要:
// 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;
}
这将让你充分利用预先加载的:
$products = Product::with('ordersCount')->get();
// then for each product you can call it like this
$products->first()->ordersCount; // thanks to the accessor
了解更多关于Eloquent accessors & mutators,
约dynamic properties,其中上述访问者模仿的行为。
当然,你可以使用简单的连接来获得完全相同的查询,就像你的例子。
我使用Laravel 5.1,我能够通过这样
$photo->posts->count()
做到这一点,在照片模式中的帖子方法看起来像这样
public function posts(){
return $this->belongsToMany('App\Models\Posts\Post', 'post_photos');
}
如果你已经有了$产品对象,您可以执行以下操作:
$rolecount = $products->roles()->count();
或者如果您正在使用热切加载:
$rolecount = $products->roles->count();
干杯。
对于未来的观众,例如Laravel 5。2,有计数的关系,而不加载它们,而不涉及您的资源模型或存取本机功能 -
在经批准的答案示例的情况下,你会放置在你的控制器:
$products = Product::withCount('orders')->get();
现在,当你通过你的看法$产品迭代,有一个orders_count
(或者,一般,只是一个{resource}_count
)上所获取的各产品记录,您可以简单地显示,就像任何其他的列值列:
@foreach($products as $product)
{{ $product->orders_count }}
@endforeach
对于相同的结果,此方法生成的数据库查询少于批准的方法,唯一涉及的模型是确保您的关系正确设置。如果您现在使用的是L5.2 +,我会改用这个解决方案。
这是非常好的 - 每个人都应该使用这个... – 2017-06-25 19:03:22
如果可以的话,我会给你+10。这应该被接受的答案。 – ElChupacabra 2017-10-01 17:21:51
该代码工作正常,即时获得所需的结果now.Thanks为你的帮助:) :)但一个问题。访问ordersCount()时,函数getOrdersCountAttribute()会自动调用吗?这两个功能如何流入? – developer34 2014-09-22 12:18:50
heck编辑 - 添加到文档的链接,在那里你可以找到你所需要的。基本上,访问器/增变器利用魔法'__get' /'__set',让你操纵模型的属性,以适应你的需求。 created_at和其他时间戳的工作方式几乎相同。 – 2014-09-22 12:23:51
我完全忘了访问者/ mutators.Thanks的参考! :) :) – developer34 2014-09-22 12:28:11