开发者

Increase a field in multiple records with cakePHP functions

开发者 https://www.devze.com 2023-03-03 02:38 出处:网络
I\'ll explain the situation. I have some \'modules\', and one of the fields is the \'position\' in the main page.If I create/edit a module with a specific position I want to check the rest 开发者_开发

I'll explain the situation.

I have some 'modules', and one of the fields is the 'position' in the main page. If I create/edit a module with a specific position I want to check the rest 开发者_开发问答of the modules which have a higher or equal position and move them one position forward.

In my solution I use the query() function of the Model.

How?

In my Module Model I have a function...

function moveModules( $includedPosition ){

    if( !is_numeric( $includedPosition ) ){
        return false;
    }

    $sql = 
          "UPDATE modules "
        . " SET modules.position = modules.position + 1 "
        . " WHERE modules.position >= $includedPosition "
    ;

    $result = $this->query(  $sql );        

}

I can use this function in the beforeSave() or in the controller wherever I want but...

I want to ask if exists a possible solution without using a custom Query.

Thanks

SOLUTION ( Thanks Headshota )

function moveModules( $includedPosition ){

    if( !is_numeric( $includedPosition ) ){
        return false;
    }

    $this->updateAll(array('Module.position'=>'Module.position + 1'), array('Module.position >='=>$includedPosition ));


}


Try using updateAll

$this->Model->updateAll(array('Model.item'=>'Model.item+1'), array('Model.id'=>1));
0

精彩评论

暂无评论...
验证码 换一张
取 消