Getting count from pivot table in laravel eloquent

前端 未结 4 1653
青春惊慌失措
青春惊慌失措 2020-12-17 01:25

I have a many to many relationship for orders and products.



        
4条回答
  •  天命终不由人
    2020-12-17 01:57

    Mind that Eloquent uses Query\Builder under the hood, so there is no such thing in Laravel, like 'query eloquent without using query builder'.

    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,

    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.

提交回复
热议问题