在Laravel中保存与更新 [英] Save vs update in laravel

查看:817
本文介绍了在Laravel中保存与更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel中的 save() update()方法之间有什么区别.

What is the difference between save() and update() method in Laravel.

在更新查询的情况下,我已经使用过save()方法,但在少数情况下,它用作更新,而在少数情况下,它用作插入查询功能.请让我知道它们之间到底有什么区别.

I have used save() method in case of update query but in few cases it acts as update and in few case it act as insert query function. Please let me know what exactly the difference between them.

推荐答案

save():您可以将其视为与sql中的INSERT等效,它将创建一个新模型(并且插入数据库)

save() : you can look to it as the equivalent of the INSERT in sql, it will create a new model (and insert it in the database)

要在数据库中创建新记录,请创建一个新的模型实例,在模型上设置属性,然后调用save方法

To create a new record in the database, create a new model instance, set attributes on the model, then call the save method

update():您可以将其视为sql中的UPDATE的等效项,它将创建一个新模型(并将其插入数据库中)

update() : you can look to it as the equivalent of the UPDATE in sql, it will create a new model (and insert it in the database)

save方法也可以用于更新数据库中已经存在的模型.要更新模型,您应该检索它,设置要更新的所有属性,然后调用save方法.同样,updated_at时间戳会自动更新,因此无需手动设置其值

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value

代码

    $flight = App\Flight::find(1);
    if (empty($flight)) {// you can do this condition to check if is empty
        $flight= new Flight;//then create new object
    }

    $flight->name = 'New Flight Name';

    $flight->save(); //this will UPDATE the record with id=1

更多信息文档

这篇关于在Laravel中保存与更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆