2014-10-03 37 views
56

我有两个相关型号:CategoryPost。 (方法scopePublished())。Laravel。在具有关系的模型中使用范围()

当我试图让与该范围内的所有类别:

$categories = Category::with('posts')->published()->get(); 

我得到一个错误:

Call to undefined method published()

类别:

class Category extends \Eloquent 
{ 
    public function posts() 
    { 
     return $this->HasMany('Post'); 
    } 
} 

帖子:

class Post extends \Eloquent 
{ 
    public function category() 
    { 
     return $this->belongsTo('Category'); 
    } 


    public function scopePublished($query) 
    { 
     return $query->where('published', 1); 
    } 

} 

回答

99

这是你怎么做内联:

$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(); 
+1

顺便说一句,如果你只想得到你发布的帖子:'Category :: whereHas('posts',function($ q){$ q-> publishe d(); }) - > get();' – tptcat 2017-01-31 18:21:07

+0

@tptcat是的。在这种情况下,也可以是'Category :: has('postsPublished')' – 2017-02-01 00:16:24