php - 在laravel的父类别中获取子类别信息
问题描述
我有多层类别,其中结构如下:
Parent
- first child
-- second child
- another child
我想要做的是,获取所有子级别的产品,Parent Page
以便我可以拥有parent, first child, second child, another child
inside的所有产品Parent
。
到目前为止我所拥有的,目前我可以获得产品,Parent, first child & another child
但我无法获得我的产品second child
。
代码
public function totalcategoriessubs($catslug) {
$category = Category::where('slug','=',$catslug)->with('childs')->first();
//testing this
// $products = Product::whereHas('category', function($q) use ($catslug,$category)
// {
// $q->where(function($q) use ($catslug,$category) {
// $q->where('slug',$catslug)->orWhere('category_id',$category->id);
// });
// })->orderBy('created_at', 'DESC')->paginate(10);
$products = Product::whereHas('category', function($q) use ($catslug, $category) {
$q->where(function($q) use ($catslug,$category) {
$q->where('slug',$catslug) //works
->WhereHas('childs') //works
->WhereHas('childs.childs') //not working
->orWhere('category_id',$category->id); //works
});
})->orderBy('created_at', 'DESC')->paginate(10);
//end testing
return view('front.categoriessubs', compact('products', 'category'));
}
楷模
Product model
public function category(){
return $this->belongsTo(Category::class);
}
Category model
public function categories()
{
return $this->hasMany(Category::class);
}
public function childs() {
return $this->hasMany(Category::class,'category_id','id') ;
}
public function parent()
{
return $this->belongsTo(Category::class,'category_id');
}
public function isParent()
{
return !$this->category_id ? true : false; // if category_id is null => is a Parent Category
}
public function products(){
return $this->hasMany(Product::class);
}
任何想法?
解决方案
您可以通过简单的技巧获得嵌套的孩子。
仅 protected $appends = ['childs', 'products'];
在模型中使用。
在 Category.php 模型中
protected appends = ['childs'];
public function categories()
{
return $this->hasMany(Category::class);
}
public function childs() {
return $this->hasMany(Category::class,'category_id','id') ;
}
public function parent()
{
return $this->belongsTo(Category::class,'category_id');
}
public function isParent()
{
return !$this->category_id ? true : false; // if category_id is null => is a Parent Category
}
public function products(){
return $this->hasMany(Product::class);
}
现在你可以让孩子们使用
Category::with('childs')->get();
希望这可以帮助。
推荐阅读
- java - 如何在 avro java 项目中处理具有不同数据库名称的多个部署环境?
- uicollectionviewcell - 需要固定大小的收集单元
- php - 从现有表生成实体
- c# - 带有条件的列表上的方法链接
- airflow - 气流告诉我删除 ~/airflow/airflow.cfg。但是当我这样做时,它会不断重新创建
- arrays - Swift Array 多次追加点击
- c++ - 在 C++ (VC++ 2010 Express) 上,双线程应用程序比单线程应用程序慢。怎么解决?
- javascript - 正则表达式将 html 标签列入白名单
- asp.net - 如何添加属性以限制 ASP.NET 上文本字段的字母?
- mysql - MySQL 5.7 简单计数查询有时快有时很慢