Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access model hasMany Relation with where condition?

I created a model Game using a condition / constraint for a relation as follows:

class Game extends Eloquent {     // many more stuff here      // relation without any constraints ...works fine      public function videos() {         return $this->hasMany('Video');     }      // results in a "problem", se examples below     public function available_videos() {         return $this->hasMany('Video')->where('available','=', 1);     } } 

When using it somehow like this:

$game = Game::with('available_videos')->find(1); $game->available_videos->count(); 

everything works fine, as roles is the resulting collection.

MY PROBLEM:

when I try to access it without eager loading

$game = Game::find(1); $game->available_videos->count(); 

an Exception is thrown as it says "Call to a member function count() on a non-object".

Using

$game = Game::find(1); $game->load('available_videos'); $game->available_videos->count(); 

works fine, but it seems quite complicated to me, as I do not need to load related models, if I do not use conditions within my relation.

Have I missed something? How can I ensure, that available_videos are accessible without using eager loading?

For anyone interested, I have also posted this issue on http://forums.laravel.io/viewtopic.php?id=10470

like image 457
Remluben Avatar asked Aug 29 '13 20:08

Remluben


1 Answers

I think that this is the correct way:

class Game extends Eloquent {     // many more stuff here      // relation without any constraints ...works fine      public function videos() {         return $this->hasMany('Video');     }      // results in a "problem", se examples below     public function available_videos() {         return $this->videos()->where('available','=', 1);     } } 

And then you'll have to

$game = Game::find(1); var_dump( $game->available_videos()->get() ); 
like image 121
Antonio Carlos Ribeiro Avatar answered Sep 28 '22 08:09

Antonio Carlos Ribeiro