Getting count from pivot table in laravel eloquent

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

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



        
相关标签:
4条回答
  • 2020-12-17 01:51

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

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

    Or if you are using eager loading:

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

    Cheers.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 02:09

    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 -

    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:

    @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.

    0 讨论(0)
  • 2020-12-17 02:16

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

     $photo->posts->count()
    

    And the posts method in Photo model looks like this

    public function posts(){
        return $this->belongsToMany('App\Models\Posts\Post', 'post_photos');
    }
    
    0 讨论(0)
提交回复
热议问题