2014-10-03 16 views
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); 
    } 

} 

risposta

99

Questo è come si fa in linea:

$categories = Category::with(['posts' => function ($q) { 
    $q->published(); 
}])->get(); 

È possibile anche definire una relazione:

public function postsPublished() 
{ 
    return $this->hasMany('Post')->published(); 
    // or this way: 
    // return $this->posts()->published(); 
} 

e poi usarlo:

//all posts 
$category->posts; 

// published only 
$category->postsPublished; 

// eager loading 
$categories->with('postsPublished')->get(); 
+1

Per inciso, se vuoi ottenere SOLO dove hai pubblicato post: 'Category :: whereHas ('posts', function ($ q) {$ q-> publishe d(); }) -> get(); ' – tptcat

+0

@tptcat si. Può anche essere 'Category :: has ('postsPublished')' in questo caso –

Problemi correlati