亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

雄辯的遞歸關系

雄辯的遞歸關系

PHP
jeck貓 2022-07-16 17:13:04
我有一個問題,我試圖獲取一個對象的所有后代并只保留那些具有特定屬性的后代。我有這些關系:    public function getChildren()    {        return $this->hasMany(self::class, 'parent_id', 'id');    }    public function allChildren()    {        return $this->getChildren()->with('allChildren');    }例如,我得到這種類型的數組:$array = [           0 => ['name' => 'aaa', 'type' => 0, 'parent' => null, 'children' => [                 1 => ['name' => 'bbb', 'type' => 1, 'parent' => null, 'children' => []],                  2 => ['name' => 'ccc', 'type' => 0, 'parent' => null, 'children' => [                       3 => ['name' => 'ddd', 'type' => 1, 'parent' => 2, 'children' => []]                        ]]                    ]],           4 => ['name' => 'eee', 'type' => 0, 'parent' => null, 'children' => []]];對于此示例,我想刪除所有屬于的對象type 1并獲得一個干凈的數組,而沒有這些對象。我真的不明白為什么可以獲得一個對象的所有后代但不能通過條件。提前致謝。
查看完整描述

2 回答

?
慕俠2389804

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');

在您的示例中,宏的工作方式如下:

  1. 過濾所有元素,其中:(type != 1
    外部數組將保持不變,因為兩個項目都有type => 0

  2. 對于當前數組的每個元素:

    • 從本指令的第一點開始,檢索該children屬性并對該子數組應用相同的過濾。

    • children用剛剛過濾的新子屬性替換該屬性。

無論如何,您應該嘗試深入研究為什么關系過濾不起作用。如果正確優化,該解決方案將更有效。


查看完整回答
反對 回復 2022-07-16
?
臨摹微笑

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;


這對我來說與上面的其他方法相同。


查看完整回答
反對 回復 2022-07-16
  • 2 回答
  • 0 關注
  • 139 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號