laravel 在laravel eloquent中从数据透视表中获取计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25973095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:08:33  来源:igfitidea点击:

Getting count from pivot table in laravel eloquent

phplaravellaravel-4counteloquent

提问by developer34

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');
    }

 }
?>

Need to fetch the number of times each product is ordered.In mysql,this task can be achieved by using the following query

需要获取每个产品的订购次数。在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

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

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??

如何使用 laravel eloquent(不使用查询构建器)来完成这项任务????如何使用 laravel eloquent 获取每个产品的订购次数?

回答by Chris Mills

For future viewers, as of Laravel 5.2, there is native functionality for counting relationships without loading them, without involving your resource model or accessors -

对于未来的查看者,从 Laravel 5.2 开始,有无需加载关系即可计算关系的本机功能,无需涉及您的资源模型或访问器 -

In the context of the example in the approved answer, you would place in your controller:

在已批准答案中的示例的上下文中,您将在控制器中放置:

$products = Product::withCount('orders')->get();

Now, when you iterate through $products on your view, there is a orders_count(or, generically, just a {resource}_count) column on each retrieved product record, which you can simply display as you would any other column value:

现在,当您在视图中遍历 $products 时,每个检索到的产品记录上都有一个orders_count(或者,一般来说,只有一个{resource}_count)列,您可以像显示任何其他列值一样简单地显示它:

@foreach($products as $product)
    {{ $product->orders_count }} 
@endforeach

This method produces 2 fewer database queries than the approved method for the same result, and the only model involvement is ensuring your relationships are set up correctly. If you're using L5.2+ at this point, I would use this solution instead.

对于相同的结果,此方法生成的数据库查询比批准的方法少 2 个,并且唯一涉及的模型是确保正确设置您的关系。如果此时您使用的是 L5.2+,我会改用此解决方案。

回答by Jarek Tkaczyk

Mind that Eloquentuses Query\Builderunder the hood, so there is no such thing in Laravel, like 'query eloquent without using query builder'.

注意在幕后Eloquent使用Query\Builder,所以在 Laravel 中没有这样的东西,比如“查询雄辩而不使用查询构建器”。

And this is what you need:

这就是你所需要的:

// 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

Read more about Eloquent accessors & mutators,

阅读有关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.

当然,您可以使用简单的连接来获得与示例中完全相同的查询。

回答by n.furnadzhiev

If you already have the $products object, you can do the following:

如果您已经拥有 $products 对象,您可以执行以下操作:

$rolecount = $products->roles()->count();

Or if you are using eager loading:

或者,如果您使用的是预先加载:

$rolecount = $products->roles->count();

Cheers.

干杯。

回答by Sajjad Ashraf

I am using Laravel 5.1 and i am able to accomplish that by doing this

我正在使用 Laravel 5.1,我可以通过这样做来实现

 $photo->posts->count()

And the posts method in Photo model looks like this

Photo模型中的posts方法看起来像这样

public function posts(){
    return $this->belongsToMany('App\Models\Posts\Post', 'post_photos');
}