2014-10-03 39 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