我使用关系的条件/约束创建了一个模型游戏,如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
什么时候使用它像这样:
$game = Game::with('available_videos')->find(1);
$game->available_videos->count();
Run Code Online (Sandbox Code Playgroud)
一切正常,因为角色是最终的集合.
我的问题:
当我试图访问它而没有急切加载
$game = Game::find(1);
$game->available_videos->count();
Run Code Online (Sandbox Code Playgroud)
抛出异常,因为它表示" 在非对象上调用成员函数count() ".
运用
$game = Game::find(1);
$game->load('available_videos');
$game->available_videos->count();
Run Code Online (Sandbox Code Playgroud)
工作正常,但对我来说似乎很复杂,因为我不需要加载相关的模型,如果我不在我的关系中使用条件.
我错过了什么吗?我怎样才能确保可以在不使用预先加载的情况下访问available_videos?
对于任何有兴趣的人,我也在http://forums.laravel.io/viewtopic.php?id=10470上发布了这个问题.