PHP NestedSet移动节点

时间:2015-11-04 16:26:40

标签: php mysql nested

拜托,你能帮我一下吗? 我试图创建自己的小型NestedSet库。一切都很好,除了三种方法:后移,前移和内移。我不知道为什么,但它仍然严重重新计算嵌套设置项目的 lft rgt ...但我无法在我的网站上看到任何问题码... 你能帮助我,我做得不好或提供一些示例嵌套集库,它实现了这三种方法来激发编辑我的代码吗? 非常感谢你。

我使用Laravel5 DB类方法,但使用普通的mysql查询没有问题。

这是我的代码:

/**
     *
     * @param $targetId
     * @param $pos
     * @param int $levelUp
     */
    public function moveNode($targetId, $pos, $levelUp = 0){

        $width = $this->rgt - $this->lft + 1; // get moved item width
        $target = $this->getLeaf($targetId);

        switch($pos) {
            case 'after':
                $newLeftPos = $target->rgt + 1;
                break;
            case 'before':
                $newLeftPos = $target->lft;
                break;
            case 'inside':
                $newLeftPos = $target->lft + 1;
                break;
        }

        $moveLength = $newLeftPos - $this->lft; // get length of move

        $newNodeLvl = $target->lvl + $levelUp;
        $nodeLvlDifference = $newNodeLvl - $this->lvl;

        // get moving node items
        // store ids of moving node items into array to use it in moving node....
        $ids = [];
        $primaryKeyName = $this->primaryKey;
        $node = DB::table($this->table)
            ->where('lft', '>=', $this->lft)
            ->where('rgt', '<=', $this->rgt)
            ->get();
        foreach($node as $nodeItem) {
            $ids[] = $nodeItem->$primaryKeyName;
        }


        // FIRSTLY I WANT TO DELETE OLD NODE SPACE SO I WILL DECREASE lft > $this->rgt AND rgt > $this->rgt BY WIDTH OF
        // MOVING NODE
        DB::table($this->table)
            ->where('lft', '>', $this->rgt)
            ->decrement('lft', $width);
        DB::table($this->table)
            ->where('rgt', '>', $this->rgt)
            ->decrement('rgt', $width);


        // NOW I WILL MAKE FREE SPACE FOR MY NODE
        // SO I NEED TO INCREASE lft AND rgt OF ITEMS WHICH ARE > $newLeftPos
        // I WILL INCREASE IT AT EACH ITEMS EXCEPT ITEMS WITH id IN $ids ARRAY (ids of items in moving node)
        DB::table($this->table)
            ->where('lft', '>=', $newLeftPos)
            ->whereNotIn($primaryKeyName, $ids)
            ->increment('lft', $width);
        DB::table($this->table)
            ->where('rgt', '>=', $newLeftPos)
            ->whereNotIn($primaryKeyName, $ids)
            ->increment('rgt', $width);

        // NOW I WILL MOVE NODE TO ITS NEW POSITION
        // ALSO I CHANGE NODE ITEMS lvl
        $nodeItems = DB::table($this->table)
            ->whereIn($primaryKeyName, $ids);
        $nodeItems->increment('rgt', $moveLength);
        $nodeItems->increment('lft', $moveLength);
        if($newNodeLvl !== 0) {
            $nodeItems->increment('lvl', $nodeLvlDifference);
        }


    }

0 个答案:

没有答案