Laravel. Use scope () en modelos con relación

101

Tengo dos modelos relacionados: Categoryy Post.

El Postmodelo tiene un publishedalcance (método scopePublished()).

Cuando trato de obtener todas las categorías con ese alcance:

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

Me sale un error:

Llamar al método indefinido published()

Categoría:

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

Enviar:

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


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

}
Ilya Vo
fuente

Respuestas:

178

Puedes hacerlo en línea:

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

También puede definir una relación:

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

y entonces:

//all posts
$category->posts;

// published only
$category->postsPublished;

// eager loading
$categories->with('postsPublished')->get();
Jarek Tkaczyk
fuente
6
Por cierto, si solo desea llegar a donde ha publicado publicaciones:Category::whereHas('posts', function ($q) { $q->published(); })->get();
tptcat
2
@tptcat sí. También puede ser Category::has('postsPublished')en este caso
Jarek Tkaczyk
¡Pregunta limpia, respuesta limpia!
Mojtaba Hn