php - Laravel sum() method on collection returning results for all items in table -
given following table
gallery +----+---------------+--------------+---------+ | id | gallery_title | viewcount | user_id | +----+---------------+--------------+---------+ | 1 | animals | 10 | 1 | | 2 | cars | 5 | 1 | | 3 | houses | 2 | 2 | +----+---------------+--------------+---------+ user +----+----------+ | id | username | +----+----------+ | 1 | bob | | 2 | james | +----+----------+ and following classes
class gallery extends model .... public function user() { return $this->belongsto('app\user'); } and
class user extends model .... public function galleries() { return $this->hasmany('app\gallery'); } calling $gallerycollections= auth::user()->galleries; returns array of collections in can iterate through
foreach ($gallerycollections $gallerycollection) { $viewcount += $gallerycollection->viewcount; } print $viewcount; #returns 15 and far works expected, correctly until point.
however if accidentally called $gallerycollection->sum('viewcount'), last value iteration, returned value 17, it's running following sql select sum('viewcount') aggregate 'gallery'.
i'm struggling understand happening here. it's if it's calling 'sum()' method on gallery class without passing in 'where' values. i'd @ least expect call sum() method on collection, instead it's going database.
is because gallery class not implement 'sum()' method, , therefore uses parent model class , ignores gallery class?
if want count through sql, then:
auth::user()->galleries()->sum('viewcount'); but, auth::user()->galleries->sum('viewcount'); sum on collection auth::user()->galleries. auth::user()->galleries() querybuilder whereas auth::user()->galleries collection of galleries of user.
Comments
Post a Comment