php - QueryBuilder: Sum values of a pivot table -


i'm new on laravel & eloquent. have users, products , votes tables on db. users can vote (0 5) on products, "many many" relationship, votes table acting pivot:

  • users: id, name, email, password
  • products: id, name, model, brand
  • votes: user_id, product_id, vote

i mapped schema this:

// user model: public function product_votes() {     return $this->belongstomany('app\product', 'votes')->withpivot('vote'); }  // product model: public function product_votes() {     return $this->belongstomany('app\user', 'votes')->withpivot('vote'); } 

so john can vote 5 on product x , 0 on product y. bob can vote 2 on product x, 3 on product y, , on...

i'm trying query products, sum of votes of each 1 of them. like:

select p.*, (sum(v.vote) / count(*)) votes products p inner join votes v on v.product_id = p.id group p.id 

how can querybuilder? mapping right?

the following trick:

product::select('products.*', db::raw('sum(vote)/count(*) votes')) ->join('votes', 'votes.product_id', '=', 'products.id') ->groupby('products.id') ->get(); 

you can see query run calling tosql() instead of get().


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -