Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
831 views
Welcome To Ask or Share your Answers For Others

1 Answer

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() );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...