問題描述
我有訂單和產(chǎn)品的多對多關(guān)系.
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');
}
}
?>
需要獲取每個產(chǎn)品的訂購次數(shù).在mysql中,這個任務(wù)可以通過使用下面的查詢來實現(xiàn)
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
以上查詢結(jié)果如下:-
id description count(products.id)
1 Shoes 3
2 Bag 2
3 Sun glasses 2
4 Shirt 2
如何使用 laravel eloquent 完成這項任務(wù)(不使用查詢構(gòu)建器)????如何使用 laravel eloquent 獲取每個產(chǎn)品的訂購次數(shù)??
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 中沒有這樣的東西,就像'查詢雄辯而不使用查詢構(gòu)建器'.
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;
}
這將讓您利用預(yù)先加載的優(yōu)勢:
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
閱讀更多關(guān)于 Eloquent accessors &變異子,
以及動態(tài)屬性,上面的訪問器模仿了這些行為.
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.
這篇關(guān)于在laravel eloquent中從數(shù)據(jù)透視表中獲取計數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!