简体   繁体   中英

count query using eloquent relation laravel

I have three tables called category , subcategory and product .

category has

id       category_name

subcategory has

id      category_id     sucategory_name

and product table has

id     category_id      subcategory_id      productname

now what i want is, i want to get the total number of product that belongs to the subcategory.

my categorymodel looks like

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Subcategory;

class Category extends Model
{
    protected $table = 'category';

    public $timestamps = false;

    public function subCategory(){

        return $this->hasMany('App\Subcategory', 'category_id');
    }
}

and my subcategory model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $table = 'subcategory';

    public $timestamps = false;


    public function products(){
        return $this->hasMany('App\Products', 'subcategory_id');
    }
}

and finally my product model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Products extends Model
{
    protected $table = 'products';

}

however I have displayed all the sub-category names that belongs to the category by doing like this in my controller

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

I have already achieved below result in my view.

category 1
  subcategory 1
  subcategory 2
  subcategory 3
category 2
  subcategory 1
  subcategory 2
  subcategory 3

Now i just want to count the number of products that belongs to the subcategory like for exampole

 category 1
      subcategory 1 (20)
      subcategory 2 (2)
      subcategory 3 (3)
    category 2
      subcategory 1 (12)
      subcategory 2 (11)
      subcategory 3 (2)

How can I achieve such result?

$categories = Category::with('subCategory')->get();
foreach ($categories as $category)
{
    echo "{$category->category_name}\n";
    foreach ($category->subCategory as $subcategory)
    {
        echo "\t{$subcategory->subcategory_name} ({$subcategory->products()->count()})\n";
    }
}

Just an idea. Adapt with your view code.

By the way, I think your product should not contain category_id because it already indirectly refer to its category via subcategory_id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM