2014-10-03 2 views
56

У меня есть две родственные модели: Category и Post.Laravel. Используйте scope() в моделях с отношением

Модель Post имеет published scope (метод scopePublished()).

Когда я пытаюсь получить все категории с этой сферы:

$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 д(); }) -> get(); ' – tptcat

+0

@tptcat да. Также может быть 'Category :: has ('postsPublished')' в этом случае –

Смежные вопросы