2 回答

TA貢獻1719條經驗 獲得超6個贊
僅收集解決方案將是這樣的(將自定義宏放在應用程序的服務提供者中):
Collection::macro('whereDeep', function ($column, $operator, $value, $nested) {
return $this->where($column, $operator, $value)->map(function ($x) use ($column, $operator, $value, $nested) {
return $x->put($nested, $x->get($nested)->whereDeep($column, $operator, $value, $nested));
});
});
然后在需要的地方調用:
$yourArray->whereDeep('type', '!=', 1, 'children');
在您的示例中,宏的工作方式如下:
過濾所有元素,其中:(
type != 1
外部數組將保持不變,因為兩個項目都有type => 0
)對于當前數組的每個元素:
從本指令的第一點開始,檢索該
children
屬性并對該子數組應用相同的過濾。children
用剛剛過濾的新子屬性替換該屬性。
無論如何,您應該嘗試深入研究為什么關系過濾不起作用。如果正確優化,該解決方案將更有效。

TA貢獻1982條經驗 獲得超2個贊
我找到了一個很好的解決方案,不需要所有這些遞歸或任何這些關系調用,所以我分享它:
使用:“gazsp/baum”
// get your object with roots method
$contents = Content::roots()->get();
// and simply run through the object and get whatever you need
// thanks to getDescendantsAndSelf method
$myArray = [];
foreach($contents as $content) {
$myArray[] = $content->getDescendantsAndSelf()->where('type', '!=', 1)->toHierarchy();
}
return $myArray;
這對我來說與上面的其他方法相同。
- 2 回答
- 0 關注
- 139 瀏覽
添加回答
舉報