使用 Laravel 更新日期时间列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49700208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:36:42  来源:igfitidea点击:

Update dateTime column with laravel

mysqldatabaselaraveleloquentlaravel-5.6

提问by L. Fox

I have a pins table in my database with a pin_date column.

我的数据库中有一个带有 pin_date 列的 pin 表。

In my migration I have this:

在我的迁移中,我有这个:

$table->dateTime('pin_date')->nullable();

$table->dateTime('pin_date')->nullable();

I have a button that points to a post route

我有一个指向邮政路线的按钮

Route::post('/pins/pin-date/{id}', 'PinsController@pinDate');

that leads to a pinDate controller method:

这导致 pinDate 控制器方法:

public function pinDate($id)
{
    $pin = Pin::find($id);

    $pin->save();
}

I want to update the pin-date column in the database to the current date and time when I click the button and hit the route. I am not really sure how to do this. Any help would be greatly appreciated! Thank you!

当我单击按钮并点击路线时,我想将数据库中的 pin-date 列更新为当前日期和时间。我不太确定如何做到这一点。任何帮助将不胜感激!谢谢!

回答by Ohgodwhy

I would do this whenever the model is saving, you can bind to the bootfunction of the modeland set it there:

只要模型是saving,我就会这样做,您可以绑定到 的boot函数model并将其设置在那里:

public static function boot()
{
    parent::boot();

    static::saving(function($pin) {
        $pin->pin_date = \Carbon::now()
    });
}

If you want to update this value instead of handling it whenever the model is saved - such as through a button click, you can use Ajax. You will need 1.) a route, 2.) a click handler, 3.) an AJAX request and 4.) a controller to handle processing the request:

如果您想在保存模型时更新此值而不是处理它 - 例如通过单击按钮,您可以使用 Ajax。您将需要 1.) 路由,2.) 单击处理程序,3.) AJAX 请求和 4.) 处理请求的控制器:

Click handler with Ajax:

使用 Ajax 的单击处理程序:

$('.btn').on('click', function(e) {
    $.ajax({
        url: '/route/to/update/my/pin' + $(this).closest('.pin').data('id')
    });
});

Then a route:

然后是一条路线:

Route::post('/route/to/update/my/pin/{id}', 'PinController@updatePinDate');

Then make the controller method and update it accordingly:

然后制作控制器方法并相应地更新它:

public function updatePinDate(Request $request, Pin $pin)
{
    $pin->pin_date = \Carbon::now();
    $pin->save();
}

If you don't want to use javascript, you can just use a standard form with the same route/controller methods:

如果您不想使用 javascript,您可以使用具有相同路由/控制器方法的标准表单:

<form action="/route/to/update/my/pin/{{ $pin->id }}" method="POST">
     {{csrf_field()}}

     <button type="Submit"> Update Pin Date </button>
</form>

回答by Marlon Adarme

public function pinDate($id)
{
    $pin = Pin::find($id);
    $pin->pin_date = \Carbon\Carbon::now();
    $pin->save();
}

I hope it works.

我希望它有效。