Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
withCount with other attributes

I have a function allArticlesCount that counts all articles that have draft 1.

$allArticlesCount = Article::where('draft', 1)->count();

I also have a function that counts the number of articles in a specific category, I use withCount , but she counts absolutely all the articles, and I only need with draft 1

$categories = BlogCategory::withCount('articles')->get();

The question is, how can I make it so that all articles that have draft 1 are counted in the $categories function?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The withCount() function, like the with() function, can use an array as its argument to allow modification of the relationship being counted. In your instance, you'd do the following:

$categories = BlogCategory::withCount(['articles' => function($query){
  $query->where('draft', 1);
}])->get();

This will return your BlogCategory instances, each with a articles_count property indicative of the number of draft articles related to each instance.

Alertnatively, you can define a draftArticles relationship:

public function draftArticles() {
  return $this->hasMany(Article::class)->where('draft', 1);
  // Note: May need to adjust `hasMany()` to reference proper FK column, etc.
}

And perform withCount() on that instead:

$categories = BlogCategory::withCount('draftArticles')->get();

Each BlogCategory instance would have a draft_articles_count property reflecting that.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda