Laravel。 在关系模型中使用scope()
我有两个相关的模型: Category和Post 。 
  Post模型具有已published范围(方法scopePublished() )。 
当我尝试使用该范围的所有类别时:
 $categories = Category::with('posts')->published()->get(); 
我收到一个错误:
调用未定义的方法
published()
类别:
 class Category extends \Eloquent { public function posts() { return $this->HasMany('Post'); } } 
post:
 class Post extends \Eloquent { public function category() { return $this->belongsTo('Category'); } public function scopePublished($query) { return $query->where('published', 1); } } 
	
这是你如何内联:
 $categories = Category::with(['posts' => function ($q) { $q->published(); }])->get(); 
你也可以定义一个关系:
 public function postsPublished() { return $this->hasMany('Post')->published(); // or this way: // return $this->posts()->published(); } 
然后使用它:
 //all posts $category->posts; // published only $category->postsPublished; // eager loading $categories->with('postsPublished')->get();