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

查看:38
本文介绍了在 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)

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

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 = AppFlight::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

更多细节doc

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

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