0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Lalavel|save()とupdate()の違い

0
Last updated at Posted at 2021-12-09

lalavelで投稿データの「更新」はsave()と update()が使えうことが分かった。

でも、どんな違いがあるのか気になったので確認してみた。

結論を言うと...

save()は、更新データがない場合「updated_at」を更新しない。
update()は、更新データがない場合でも「updated_at」を更新する。

save()を使った場合

コントローラーのupdateメソッドは以下のとおり

controller.php
public function update(PostRequest $request, $id)

...処理...

//入力値をセット
$post->title=$request->title;
$post->body=$request->body;
  
//更新      
$post->save(); 

実際のテーブルの中身を見てみよう。

これが最初のテーブルの中身
スクリーンショット 2021-11-18 15.25.12.png

何も変更しないで「更新」ボタン押した時、「updated_at」は更新せず
スクリーンショット 2021-11-18 15.25.38.png

タイトルとか本文を変更し「更新」ボタン押した時には、「updated_at」を更新した
スクリーンショット 2021-11-18 15.25.59.png

update()を使った場合

コントローラーのupdateメソッドは以下のとおり

controller.php
public function update(PostRequest $request, $id)

...処理...

Post::where('id',$id)->update([
  'title'=>$request->title,
  'body'=>$request->body
]);

実際のテーブルの中身を見てみよう。

これが最初のテーブルの中身
スクリーンショット 2021-11-18 15.28.06.png

何も変更しないで「更新」ボタン押した時、「updated_at」は更新した
スクリーンショット 2021-11-18 15.28.27.png

タイトルとか本文を変更し「更新」ボタン押した時にも、「updated_at」を更新した
スクリーンショット 2021-11-18 15.29.10.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?