Count lines laravel

1

I'm using Laravel 5.2 and I have a lot of doubts to tell the lines about my search. I need to return the number of products within Categorias and SubCategorias .

My relationships are as follows, in the Product table I have a CdSubCategory field that refers to the CdSubCategory of the SubCategory table, besides this I have within the CategoryCode the category code, this due to the relationship (one for many in relation category and subcategory) and in the images below.

In my product model I did this:

class Produto extends Model
{
 use SoftDeletes;

 protected $fillable = [
    'CdSubCategoria',
    'NmProduto',
    'DscProduto',
    'VlUnit',
    'UnitEmEstoque',
    'FlgDescontinuado',
    'FlgProdutoVisivel',
    'Visivel_Ini',
    'Visivel_Fim',
    'FlgPontua',
    'QtdPontos',
    'MaxPontosPorSubCategoria'
];
protected $primaryKey = 'CdProduto';
protected $dates = ['deleted_at'];

public function subCategoria()
{
    return $this->belongsTo('App\SubCategoria','CdSubCategoria','CdSubCategoria');
}

public function imagens(){
    return $this->hasMany('App\Imagem', 'CdProduto', 'CdProduto');
}

public function lotes(){
    return $this->hasMany('App\LoteProduto', 'CdProduto', 'CdProduto');
}

public function tipo_produto_embalagem(){
    return $this->belongsTo('App\TipoProdutoEmbalagem', 'CdProduto', 'CdProduto');
 }
}

Ha no model Category:

class Categoria extends Model
{
 use SoftDeletes;

protected $fillable = ['NmCategoria', 'DscCategoria'];
protected $primaryKey = 'CdCategoria';
protected $dates = ['deleted_at'];

public function subCategorias()
{
    return $this->hasMany('App\SubCategoria','CdCategoria','CdCategoria');
 }
}

And finally in the Subcategory model:

class SubCategoria extends Model
{
 use SoftDeletes;

 protected $fillable = ['CdCategoria','NmSubCategoria', 'DscSubCategoria', 'FlgPontua', 'QtdPontos', 'MaxPontosCategoria'];
 protected $primaryKey = 'CdSubCategoria';
 protected $dates = ['deleted_at'];

 public function categoria()
 {
    return $this->belongsTo('App\Categoria','CdCategoria','CdCategoria');
 }

 public function produtos(){
    return  $this->hasMany('App\Produto','CdSubCategoria','CdSubCategoria');
 }
}

Count the number of products within a subcategory I got statically, and did as follows:

 $count = Produto::where('CdSubCategoria','3')->count();
 dd($count);

But I have some problems like:

  • I need to count all subCategorias , ie this count needs to be dynamic. Remember that I need this information in my view, because I'm using it like this:

    CATEGORY NAME (PRODUCT QTY)

  • I also need to count the number of products per subCategoria product required by category (Remembering this relationship is one for many)

  • OBS.

      

    Ideally, this information should come with my model. Ex: the same way I access $produto->imagens could access $subCategoria->qtd and $categoria->qtd

        
    asked by anonymous 17.10.2016 / 16:54

    2 answers

    1
      

    1) I need to count all subcategories, ie this count needs to be dynamic. It is worth remembering that I need this information in my view, since I am using it like this: CATEGORY NAME (PRODUCT QTD)

    The withCount > so that it works correctly in your case it has to be SubCategoria to Produto :

    $s = new SubCategoria();
    $r = $s->withCount("produtos")->get();
    var_dump($r);
    

    return will show something:

    [
        {
            "CdSubCategoria": 1,
            "CdCategoria": 1,
            "NmSubCategoria": "Sub Categoria 1",
            "DscSubCategoria": "Sub Categoria 1",
            "deleted_at": null,
            "produtos_count": 2
        },
        {
            "CdSubCategoria": 2,
            "CdCategoria": 1,
            "NmSubCategoria": "Sub Categoria 2",
            "DscSubCategoria": "Sub Categoria 2",
            "deleted_at": null,
            "produtos_count": 1
        },
        {
            "CdSubCategoria": 3,
            "CdCategoria": 2,
            "NmSubCategoria": "Sub Categoria 3",
            "DscSubCategoria": "Sub Categoria 3",
            "deleted_at": null,
            "produtos_count": 1
        }
    ]
    
      

    2) I need in addition to count the number of products per subcategory, you need product by categories (Remember that this relationship is one for many)

    $c = new Categoria();
    $r = $c
         ->join('sub_categorias','sub_categorias.CdCategoria','=','categoria.CdCategoria')
         ->join('produtos','produtos.CdSubCategoria','=','sub_categorias.CdSubCategoria')
         ->selectRaw('categoria.CdCategoria,categoria.NmCategoria, count(*) count_produto_cat')
         ->groupBy(['categoria.CdCategoria','categoria.NmCategoria'])
         ->get();
    

    return will show something:

    [
        {
            "CdCategoria": 1,
            "NmCategoria": "Categoria 1 ",
            "count_produto_cat": 3
        },
        {
            "CdCategoria": 2,
            "NmCategoria": "Categoria 2",
            "count_produto_cat": 1
        }
    ]
    

    Note: Note that Produtos is not directly related to Categoria

        
    18.10.2016 / 15:30
    1

    I think what you want can be done with withCount . This method you use to bring the count of relationships.

    See:

    $produtos = Produto::with('imagens')->withCount('imagens')->where(['created_at' => new DateTime])->get();
    

    In order to access the count value, simply add _count in front of the relationship name:

     $produto->imagens_count; // 3
    
        
    18.10.2016 / 15:11