56
Ho due modelli correlati: Category
e Post
.Laravel. Utilizzare scope() nei modelli con relazione
Il modello Post
ha un ambito published
(metodo scopePublished()
).
Quando provo ad ottenere tutte le categorie con tale scope:
$categories = Category::with('posts')->published()->get();
ottengo un errore:
Call to undefined method
published()
Categoria:
class Category extends \Eloquent
{
public function posts()
{
return $this->HasMany('Post');
}
}
Messaggio:
class Post extends \Eloquent
{
public function category()
{
return $this->belongsTo('Category');
}
public function scopePublished($query)
{
return $query->where('published', 1);
}
}
Per inciso, se vuoi ottenere SOLO dove hai pubblicato post: 'Category :: whereHas ('posts', function ($ q) {$ q-> publishe d(); }) -> get(); ' – tptcat
@tptcat si. Può anche essere 'Category :: has ('postsPublished')' in questo caso –