4 回答

TA贡献1921条经验 获得超9个赞
您可以通过以下方式修复它:
建立递归关系:(请在此处参考 Alex Harris 的回答)
// recursive, loads all descendants
// App\Category
public function childrenRecursive()
{
return $this->childs()->with('childrenRecursive');
}
$data = Category::with(['products', 'childrenRecursive', 'childrenRecursive.products'])->where('id', 2)->get()->toArray();
#Edit:提取产品列表
在控制器中定义Flatten laravel 递归关系集合(树集合)函数
public function flatten($array)
{
$flatArray = [];
if (!is_array($array)) {
$array = (array)$array;
}
foreach($array as $key => $value) {
if (is_array($value) || is_object($value)) {
$flatArray = array_merge($flatArray, $this->flatten($value));
} else {
$flatArray[0][$key] = $value;
}
}
return $flatArray;
}
然后为了只有产品项目
$data = Category::with(['products', 'childrenRecursive', 'childrenRecursive.products'])->where('id', 2)->get()->toArray();
$flatten = $this->flatten($data);
foreach ($flatten as $key => $fl) {
// eliminate categories from $flatten array
if (!array_key_exists('category_id', $fl)) {
unset($flatten[$key]);
}
}
$product = array_values($flatten);

TA贡献1780条经验 获得超1个赞
一种选择是使用类似laravel-adjacency-list 的东西。这将允许您使用CTE递归加载关系。
以下是设置您的步骤(在撰写本文时)
跑composer require staudenmeir/laravel-adjacency-list:"^1.0"
将HasRecursiveRelationships特征添加到您的Category模型中:
use Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;
class Category extends Model
{
use HasRecursiveRelationships;
...
}
将您的查询更改为:
Category::with('descendants.products')->where('id', $id)->first(); //$id being the id of the parent category you want to get.
如果您只想获取某个类别中/下的产品,您可以执行以下操作:
Product::whereHas('category', function ($query) use ($category) {
$query->whereIn('categories.id', $category->descendantsAndSelf()->select('id')->getQuery());
})->get();
有关如何使用的更多信息,laravel-adjacency-list请参阅文档。

TA贡献1788条经验 获得超4个赞
$categories = Category::whereParentId(null)->with('children.children.children')->get();
并查看您可以使用 foreach 循环显示项目

TA贡献1775条经验 获得超8个赞
如果你使用 ORM 雄辩的关系
public function categoriesProduct(ProductCategory $category)
{
$categories = ProductCategory::where('parent_id', $category->id)
->orWhere('id', $category->id)
->latest()
->get();
return view('categoryProduct', compact('categories', 'category'));
}
- 4 回答
- 0 关注
- 240 浏览
添加回答
举报