如何解决Laravel类别树-顺序子项
我有一个带有类别和子项的Laravel项目-我的模型中有此功能:
public static function tree() {
return Category::with(implode('.',array_fill(0,100,'children')))->where('parent_id','=',NULL)->get();
}
然后我打电话给
$categories = Category::tree();
在视图上,我有:
@foreach($categories as $index => $category)
{{ $category->title }}
@foreach($category['children'] as $child)
{{ $child->title }}
@endforeach
@endforeach
那很好,但是我现在尝试按字母顺序对孩子们进行排序。
我已经尝试过了:
public static function tree() {
return Category::with([implode('.','children')) => function($query) {
$query->orderBy('title','ASC');
}])->where('parent_id',NULL)->get();
}
我也尝试过return Category::with(implode('.',NULL)->orderBy('title)->get();
,但这只是订购父类别。
但是它没有对它们进行排序。任何人有任何想法吗?
谢谢。
-编辑-
按照蒂姆的建议,我现在有了:
public function children() {
return $this->hasMany('App\Category','parent_id','id');
}
public function childrenCategories()
{
return $this->children()->with('childrenCategories');
}
然后...
$categories = Category::with(['childrenCategories' =>
function($query) {
$query->orderBy('title','ASC');
}])->where('parent_id',NULL)->get();
可以工作,但不能订购。有什么建议吗?
解决方法
如果您不关心性能,可以尝试在视图中sort子集。
@foreach($category['children']->sortBy('title') as $child)
{{ $child->title }}
@endforeach
但这是一个非常非常非常糟糕的解决方案!
好的方法始于重组类别的整个结构。我更喜欢嵌套集。 Laravel有一个很酷的实现。 https://github.com/etrepat/baum
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。