aumbadgah
aumbadgah

Reputation: 70

update single row from model in cakephp

I'm trying loop through records in my model and update their serial numbers. According to the tempArray all the values should be in order but the updating part isn't happening. Are there restrictions to using read/set/save in model or what am I missing?

    $tempArray['highest serial'] = $highest['Paragraph']['serial_number'];
    for( $i=$paragraph['Paragraph']['serial_number']; $i<$highest['Paragraph']['serial_number']; $i++ ){
        $current = $this->find('first', array(
            'fields' => array(
                'Paragraph.id',
                'Paragraph.serial_number'
            ),
            'conditions' => array(
                'Paragraph.webpage_id' => $paragraph['Paragraph']['webpage_id'],
                'Paragraph.list_element' => $paragraph['Paragraph']['list_element'],
                'Paragraph.serial_number' => ($i + 1)
            )
        ));
        $tempArray['i ' . $i . ' id'] = $current['Paragraph']['id'];
        $tempArray['i ' . $i . ' serial'] = $current['Paragraph']['serial_number'];
        $this->create($current);
        // $this->read('serial_number', $current['Paragraph']['id']);
        // $this->id = $current['Paragraph']['id'];
        $this->set('serial_number', $i);
        $this->save();
    }
    return $tempArray;

While the output from tempArray is ( [highest serial] => 2 [i 1 id] => 7 [i 1 serial] => 2 ) the serial_number of the record with id=7 is not updated.

Haelp!

Edit: Changed read() into create() as suggested. No SQL or PHP errors occur, and tempArray values are correct, but no changes updated to database record. Any help would be greatly appreciated.

Edit2: IT'S WORKING! Finally.. For some reason I only managed to get it working using saveField()

    for( $i=$paragraph['Paragraph']['serial_number']; $i<getHighestSerial($paragraph); $i++ ){
        $current = $this->find('first', array(
            'fields' => array(
                'Paragraph.id',
                'Paragraph.serial_number'
            ),
            'conditions' => array(
                'Paragraph.webpage_id' => $paragraph['Paragraph']['webpage_id'],
                'Paragraph.list_element' => $paragraph['Paragraph']['list_element'],
                'Paragraph.serial_number' => ($i + 1)
            )
        ));         
        $this->id = $current['Paragraph']['id'];
        $this->saveField('serial_number', $i);
    }

Upvotes: 1

Views: 700

Answers (1)

Dave
Dave

Reputation: 29121

According to the CakePHP Book

When calling save in a loop, don’t forget to call create().

Upvotes: 1

Related Questions