4 回答
TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以通過(guò)以下方式修復(fù)它:
建立遞歸關(guān)系:(請(qǐng)?jiān)诖颂巺⒖?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:提取產(chǎn)品列表
在控制器中定義Flatten laravel 遞歸關(guān)系集合(樹(shù)集合)函數(shù)
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;
}
然后為了只有產(chǎn)品項(xiàng)目
$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貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
一種選擇是使用類似laravel-adjacency-list 的東西。這將允許您使用CTE遞歸加載關(guān)系。
以下是設(shè)置您的步驟(在撰寫(xiě)本文時(shí))
跑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.
如果您只想獲取某個(gè)類別中/下的產(chǎn)品,您可以執(zhí)行以下操作:
Product::whereHas('category', function ($query) use ($category) {
$query->whereIn('categories.id', $category->descendantsAndSelf()->select('id')->getQuery());
})->get();
有關(guān)如何使用的更多信息,laravel-adjacency-list請(qǐng)參閱文檔。
TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
$categories = Category::whereParentId(null)->with('children.children.children')->get();并查看您可以使用 foreach 循環(huán)顯示項(xiàng)目
TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果你使用 ORM 雄辯的關(guān)系
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 關(guān)注
- 304 瀏覽
添加回答
舉報(bào)
