我想更新模型上的字段 ( status
)。我会从数据库中检索并为 status
分配一个新值柱子。但是在模型保存后,我看到另一个日期字段( published_at
)也更改为与 updated_at
相同.
当用户单击链接时运行的操作为 http://localhost/dashboard/gallery/publish/1 .
我不知道为什么published_at
自动更新,与 updated_at
相同?
这是 Controller 代码 :
<?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');
}
}
?>
和 画廊模型 :
<?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'];
}
?>
和 迁移功能 :
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');
});
}
更新
我在迁移功能中看到这个配置有问题,在这里:
$table->timestamp('published_at');
这条语句创建了这样的 SQL:
CREATE TABLE `gallery` (
...
`published_at` Timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
...
)
那么,如何设置一个时间戳字段,它不是当前时间自动更新的?
更新 2
大功告成,我修改迁移,直接用
dateTime
而不是 timestamp
.使用它,
$table->dateTime('published_at');
,此语句不会在 CURRENT_TIMESTAMP 上自动更新。
最佳答案
看起来正在发生的事情是 MySQL(或您使用的任何数据库)正在更新日期,而不是 Laravel。
你需要改变:
$table->timestamp('published_at');
到:
$table->dateTime('published_at');
然后做一个
php artisan migrate:refresh
回滚并重新创建您的表。
关于laravel - 为什么 Laravel 5 会自动更新我的日期字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35767397/