Php 在Laravel查询中从计数器隐藏未发布的项目
我将显示主类别下的所有子类别。在每个子类别上都有一个计数器,指示分配了多少项Php 在Laravel查询中从计数器隐藏未发布的项目,php,laravel,laravel-5,Php,Laravel,Laravel 5,我将显示主类别下的所有子类别。在每个子类别上都有一个计数器,指示分配了多少项 Main Category - Sub Category (1) - Sub Category (3) - etc 当前的问题是一个项目可以发布和取消发布。当项目尚未发布时,我不想在计数器上显示它。items表中的列为published,已发布接受1,未发布接受0 这是我必须在第页向他们展示的内容 HomeController.php $allCategories = Category::where
Main Category
- Sub Category (1)
- Sub Category (3)
- etc
当前的问题是一个项目可以发布和取消发布。当项目尚未发布时,我不想在计数器上显示它。items
表中的列为published
,已发布接受1
,未发布接受0
这是我必须在第页向他们展示的内容
HomeController.php
$allCategories = Category::where('parent_id', 0)->has('children.item')
->with(['children'=> function($query){
$query->withCount('item');
}])
->get()
->each(function($parentCategory){
$parentCategory->item_count = $parentCategory->children->sum(function ($child) { return isset($child->item_count)?$child->item_count:0;});
});
myitem.php模型
public function category()
{
return $this->belongsTo('App\Category');
}
public function item()
{
return $this->hasMany('App\Item','category_id');
}
public function parent()
{
return $this->belongsTo('App\Category', 'id', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id', 'id');
}
My Category.php模型
public function category()
{
return $this->belongsTo('App\Category');
}
public function item()
{
return $this->hasMany('App\Item','category_id');
}
public function parent()
{
return $this->belongsTo('App\Category', 'id', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id', 'id');
}
我试图直接将其添加到查询中,但没有任何区别
$query->withCount('item')->where('published', 1);
您必须在
Category.php
model的关系函数item
中添加where条件
代码如下:
public function item()
{
return $this->hasMany('App\Item','category_id')->where('published', 1);
}
嗯,那很容易。非常感谢。抱歉,关于这一点的快速问题:是否也可以隐藏空的
children
,例如,您无法获取App\Category
大于0Hm的子项,我不确定是否理解。我需要获取App\Item大于0的位置。在这种情况下,您可以添加另一个where toItem()
,其中category\u id
大于0。