2

I have this little piece of code to update the position of element

public function moveUp($id) {

        $row = $this->find($id)->current();

        $kategoria = $row->kategoria;
        $position = $row->position;

        if($position > 1) {

            $data1 = array(
                    'position'  => new Zend_Db_Expr('position - 1')
                );
            $where1['id = ?'] = $id;

            $this->getDefaultAdapter()->update($this->_name, $data1, $where1);  

            $data2 = array(
                    'position'  => new Zend_Db_Expr('position + 1')
                );

            $where2['position = ?'] = $position - 1;
            $where2['kategoria = ?'] = $kategoria;  

            $this->getDefaultAdapter()->update($this->_name, $data2, $where2);

        }
    }

The problem is that only second update is executed and first one does nothing. If I comment out second update then the first update works fine. Why is that?

Also should I check for the next smaller / bigger position instead of just +/- 1 ? That is assuming the code in other parts of application don't make gaps in position column.

4

1 回答 1

2

好的,想通了。第一次更新后,两行都相同position,因此第二次更新影响两行而不是一个。

通过添加修复它

$where2['id != ?'] = $id;  
于 2012-09-13T13:33:34.350 回答