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