Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

count child products for each parent Product laravel

//First you need to set relations in Products Models
class ParentProduct extends Model
{
  public function childProduct() {
          return $this->hasMany(ChildProduct::class, 'parent', 'id')->orderBy('rang', 'desc');
      }
}

class ChildProduct extends Model
{
  public function parentProduct() {
          return $this->hasOne(ParentProduct::class, 'id', 'parent')->orderBy('rang', 'desc');
      }
}

//Than call it In ProductsController
$allProducts = ParentProduct::with(['childProduct'])->orderByDesc('rang')->get()

//Than Use it In blade
@foreach($allProducts as $product)
	{{ count($product->$childProduct) }}
@endforeach
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #count #child #products #parent #Product #laravel
ADD COMMENT
Topic
Name
7+8 =