如何统计属于(蛞蝓)类别Laravel 8的所有产品



我是Laravel的初学者。我需要一点帮助。我有一个index.blade.php文件,其中显示所有类别名称。当我点击它会生成一个链接,我有所有的产品,在这个类别。因此,我想只计算那些属于类别的产品,并在index.blade.php上显示该数字。谢谢你的帮助。

Route::get('view-category/{slug}', [ProductsController::class,'viewcategory']);

productsController:

public function viewcategory($slug){
if(Category::where('slug', $slug)->exists()){
$category = Category::where('slug', $slug)->first();
$products = Products::where('cateId', $category->id)->where('status','1')->get();
return view('admin.products.display', compact('category','products'));
}
else{
return redirect('/dashboard')->with('status',"Slug does not exist");
}
}

分类模型:

class Category extends Model
{
use HasFactory;
protected $table = "categories";
protected $fullable = [
'name',
'slug',
'description',
'status',
'popular',
];
public function products(){
return $this->belongsTo(Products::class, 'id', 'cateId');
}
}

index.blade.php:

<thead>
<tr>
<th></th>
<th>Product Name</th>
<th>Category</th>
<th>Sub Category</th>
<th>Variations</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach($category as $item)
<tr>
<td class="control" tabindex="0"></td>
<td>{{$item->products->productName}}</td>
<td>{{$item->name}}</td>
<td>{{$item->subCategory}}</td>
<td>{{$item->counter}}</td>
<td></td>
<td></td>
</tr>
@endforeach
</tbody>
</table>

您仍然可以在刀片文件中调用关系,因此,如果您正确设置了产品关系,您只需要将索引刀片更改为

<td>{{$item->products()->count()</td>

如果你有没有任何产品的类别,在显示计数之前把这个放在刀片中检查(这是一个内联的If else语句)

<td>{{$item->products ? $item->products()->count() : 'N/A'}}</td>

在您的刀片文件中,在foreach

之前添加这一行
@if( $category->posts->count() )
//your @foreach code here
@endif

最新更新