Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 5 在laravel中保存vs更新_Laravel 5 - Fatal编程技术网

Laravel 5 在laravel中保存vs更新

Laravel 5 在laravel中保存vs更新,laravel-5,Laravel 5,Laravel中的save()和update()方法有什么区别 我在update查询中使用了save()方法,但在少数情况下它充当update,在少数情况下它充当insert查询函数。请告诉我它们之间的具体区别。这些方法都允许您将数据保存到数据库中 创建数据库表中当前不存在的新模型时,save()方法执行INSERT: $flight = new Flight; $flight->name = $request->name; $flight->save(); // i

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


我在update查询中使用了save()方法,但在少数情况下它充当update,在少数情况下它充当insert查询函数。请告诉我它们之间的具体区别。

这些方法都允许您将数据保存到数据库中

创建数据库表中当前不存在的新模型时,
save()
方法执行
INSERT

 $flight = new Flight;

 $flight->name = $request->name;

 $flight->save(); // it will INSERT a new record
当您的模型已经存在于数据库中时,它还可以起到更新的作用。因此,您可以获取模型,修改一些属性,然后
保存()
它,实际执行数据库的
UDPATE

$flight = App\Flight::find(1);

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

$flight->save(); //this will UPDATE the record with id=1
update()
方法允许您以更方便的方式更新模型:

App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]); // this will also update the record
因此,您甚至不需要将检索到的模型分配给任何变量。更新的属性作为参数传递


示例和更多信息。

在@ginopane讲述的差异中,只有一件事没有说出来,那就是如果对
查询生成器结果使用update方法,那么laravel将忽略模型的
$filleble
$guard
数组。如果要使用
Input::all()
作为更新的参数,这一点尤为重要:

Post::where('id', $id)->update(Input::all());
因此,在本例中,如果使用
App\Flight::where('active',1)->update(Input::all())
数据库中的所有内容都将更新,即使您将其放入
$filleble
。因此,请确保在
雄辩实例
上使用
保存
更新
方法,而不是查询生成器方法。即使用户提交了您不想在数据库表中插入或更新的字段,以下代码也可以:

// User model
protected $fillable = ['email', 'name'];


// controller
public function update($id)
{
    $user = User::findOrFail($id);

    // validate the input here, use Request to do the job or whatever you like

    $user->update(Input::all());

    return view('some_view')->with('notice', 'user updated');
}
现在,不管表单在这里传递的是什么,只有
name
email
会被更新

希望这个完整的@ginopane答案save():您可以将其视为sql中插入的等价物,它将创建一个新模型(并将其插入数据库)

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

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

save方法还可用于更新数据库中已存在的模型。要更新模型,应该检索它,设置要更新的任何属性,然后调用save方法。同样,时间戳处更新的_将自动更新,因此无需手动设置其值

代码


有关更多详细信息,请参见插入/更新时的并发问题。创建一个合理的书写界面和处理重复是值得的。请尝试解释这种原因,并继续回答这个问题。
    $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