php - Laravel Eloquent how to return one to many to many collection -


is possible eloquent relation based on one->many->many relationship? in below example, want of gallery_votes given user.

users +----+---------------+ | id |  user_name    | +----+---------------+ |  1 | bob           | |  2 | sam           | +----+---------------+  galleries +----+---------------+-----------+ | id |  gallery_name |  user_id  | +----+---------------+-----------+ |  1 | alaska pics   |        1  | |  2 | texas pics    |        1  | |  3 | california    |        2  | |  4 | cars          |        2  | +----+---------------+-----------+  gallery_votes +----+---------------+--------+ | id |  gallery_id   |  vote  | +----+---------------+--------+ |  1 |           1   |     1  | |  2 |           1   |     1  | |  3 |           1   |     1  | |  4 |           2   |     1  | +----+---------------+--------+ 

the relationships setup follows.

class user extends model implements authenticatablecontract, canresetpasswordcontract {{     ...     public function galleries()     {         return $this->hasmany('app\gallery');     } } 

and

class gallery extends model {     ....     public function votes()     {         return $this->hasmany('app\galleryvote');     }  } 

$user->galleries returns collection of associated galleries, works correctly. , $gallery->votes returns collection of associate votes, works correctly. $user->galleries->votes gives

undefined property: illuminate\database\eloquent\collection::$votes on line 1 

is i'm trying possible straight laravel? or need write sql directly?

the "has many through" relation provides convenient short-cut accessing distant relations via intermediate relation.

class user extends model implements authenticatablecontract, canresetpasswordcontract {{     ...     public function galleries()     {         return $this->hasmany('app\gallery');     }      public function votes()      {         return $this->hasmanythrough('app\galleryvote', 'app\gallery');     } } 

now $user->votes return votes user. remember need create galleryvote eloquent model well.

you can read more type of relation, example usage in documentation.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -