Posted at

[CakePHP 2.x]単一カラムを更新するModel::saveField()を試す

More than 3 years have passed since last update.


試み


  • 比較用にModel::save()と、単一カラムを更新するModel::saveField()を試す。


事前準備


テーブルを用意

CREATE TABLE comments(

id SERIAL NOT NULL PRIMARY KEY,
comment TEXT NOT NULL,
created TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
modified TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);


データを用意

INSERT INTO comments(comment) VALUES

('Comment 1'),
('Comment 2');


モデルを用意

app/Model/Comment.php ※bakeで作る


ビューを用意

app/View/Comments/example.ctp

<pre>

<?php print_r($before); ?>
</pre>
<pre>
<?php print_r($after); ?>
</pre>


コントローラを用意

app/Controller/CommentsController.php ※bakeで作る


Model::save()で試す

class CommentsController extends AppController {

public function save() {
$comment = __FUNCTION__;

$this->Comment->id = 1;

$this->set('before', $this->Comment->read());

$this->Comment->save(array(
'Comment' => array(
'comment' => $comment,
),
));

$this->set('after', $this->Comment->read());

$this->render('example');
}
}


  • 実行結果

Array

(
[Comment] => Array
(
[id] => 1
[comment] => Comment 1
[created] => 2015-02-22 10:23:34.10898
[modified] => 2015-02-22 10:23:34.10898
)

)
Array
(
[Comment] => Array
(
[id] => 1
[comment] => save
[created] => 2015-02-22 10:23:34.10898
[modified] => 2015-02-22 10:23:34.10898
)

)

UPDATE "public"."comments"

SET "id" = 1, "comment" = 'save', "created" = '2015-02-22 10:23:34.10898', "modified" = '2015-02-22 10:23:34.10898'
WHERE "public"."comments"."id" = 1


  • save()だとread()で読み込んだデータも更新に含まれる。

  • 使い方によっては$fieldListも合わせて使う。


Model::saveField()で試す

class CommentsController extends AppController {

public function saveField() {
$comment = __FUNCTION__;

$this->Comment->id = 2;

$this->set('before', $this->Comment->read());

$this->Comment->saveField(
'comment',
$comment
);

$this->set('after', $this->Comment->read());

$this->render('example');
}
}


  • 実行結果

Array

(
[Comment] => Array
(
[id] => 2
[comment] => Comment 2
[created] => 2015-02-22 10:23:34.10898
[modified] => 2015-02-22 10:23:34.10898
)

)
Array
(
[Comment] => Array
(
[id] => 2
[comment] => saveField
[created] => 2015-02-22 10:23:34.10898
[modified] => 2015-02-22 02:25:54
)

)

UPDATE "public"."comments"

SET "comment" = 'saveField', "modified" = '2015-02-22 02:25:54'
WHERE "public"."comments"."id" = 2


  • saveField()だと対象とするcommentカラムとmodifiedカラムが更新される。