Dav*_*vuz 10 timestamp laravel laravel-5.2
我想更新status模型上的field().我将从DB检索并为status列分配新值.但是在模型保存之后,我看到另一个日期字段(published_at)也改为相同updated_at.当用户单击链接为http:// localhost/dashboard/gallery/publish/1时,操作将运行.
我不知道为什么published_at更新的汽车和它一样updated_at?
这是控制器代码:
<?php
class GalleryController extends Controller
{
/**
* Approve to publish the gallery on the web.
*
* @param int $id
* @return Response
*/
public function getPublish($id)
{
$gallery = Gallery::whereId($id)->firstOrFail();
$gallery->status = Gallery::STT_PUBLISH;
$gallery->save();
return redirect( route('backend::gallery.edit',[$gallery->id]) )->with('status', 'Done');
}
}
?>
Run Code Online (Sandbox Code Playgroud)
和图库模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Gallery extends Model
{
use SoftDeletes;
protected $table = 'gallery';
protected $fillable = ['title', 'slug', 'content', 'category_id', 'type'];
protected $guarded = ['published_at','creator_id','thumbnail'];
protected $dates = ['deleted_at', 'published_at'];
}
?>
Run Code Online (Sandbox Code Playgroud)
和迁移功能:
public function up()
{
Schema::create('gallery', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('slug')->unique();
$table->tinyInteger('type')->unsigned();
$table->integer('category_id')->unsigned()->default(0);
$table->string('thumbnail');
$table->string('title');
$table->text('content');
$table->integer('status')->unsigned()->default(0);
$table->timestamp('published_at');
$table->integer('creator_id')->unsigned();
$table->timestamps();
$table->index(['slug']);
$table->softDeletes();
});
Schema::table('gallery', function (Blueprint $table) {
$table->foreign('category_id')->references('id')->on('category');
$table->foreign('creator_id')->references('id')->on('users');
});
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
我在Migration函数中看到这个配置会产生问题,这里:
$table->timestamp('published_at');
这个语句创建了SQL:
CREATE TABLE `gallery` (
...
`published_at` Timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
...
)
Run Code Online (Sandbox Code Playgroud)
那么,如何设置一个时间戳字段,这不是当前时间的自动更新?
更新2
完成后,我修改了迁移,只需使用dateTime而不是timestamp.
使用它,$table->dateTime('published_at');此语句不会在CURRENT_TIMESTAMP上自动更新.
看起来正在发生的事情是MySQL(或您使用的任何数据库)正在更新日期,而不是Laravel。
您需要更改:
$table->timestamp('published_at');
Run Code Online (Sandbox Code Playgroud)
至:
$table->dateTime('published_at');
Run Code Online (Sandbox Code Playgroud)
然后执行php artisan migrate:refresh回滚并重新创建表。
小智 7
这篇文章很旧,但是对于任何遇到此问题的人来说,这是最简单的解决方案。在您的迁移中,时间戳记字段必须为空。然后,在此字段上将没有自动更新触发器。
$table->timestamp('published_at')->nullable();
Run Code Online (Sandbox Code Playgroud)
无需使用$table->dateTime()代替$table->timestamp()。
| 归档时间: |
|
| 查看次数: |
5679 次 |
| 最近记录: |