【问题标题】:How to set updated_at into integer column?如何将 updated_at 设置为整数列?
【发布时间】:2021-01-13 16:10:22
【问题描述】:

我在插入 update_at、created_at、deleted_at 类型为整数的表时遇到问题。但据我了解,这些列的默认类型为 datetime,当我更新注释时,出现类似 Invalid text representation: 7 ERROR: invalid input syntax for type integer: "2020-09-28 04:21:06" 的错误。因此,当我创建一个新笔记时,我添加了这个 updated_at = Carbon::now()->timestamp; 但它不起作用,我无法更改表的结构和列的类型

【问题讨论】:

  • 当您尝试使用此updated_at = Carbon::now()->timestamp; 时遇到什么错误?
  • 请去数据库..将类型updated_at 更改为timestamp并设置默认nullcurrent timestamp ...
  • 为什么updated_at设置为整数?它应该是timestamp,去 pogres admin 并检查列格式。在您的迁移中,您有 $table->timestamps(); 或者您已修改 updated_at
  • 默认类型不是 datetime ,默认格式是 timestamp 两者不同。能否分享一下迁移文件?
  • 请尝试一下。date('Y-m-d h:i:s ', strtotime($date));date('Y-m-d h:i:s');

标签: laravel postgresql eloquent


【解决方案1】:

如果列应该是timestamp with/without time zone,您可以简单地使用current_timestamplocaltimestamp

这样,你将不得不使用更复杂的

EXTRACT(epoch FROM current_timestamp)`

【讨论】:

    【解决方案2】:

    检查Date mutators 文档并在您的模型中设置dateformat

    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
    

    修改模型的迁移:

    替换

    $table->timestamps(); 
    

    $table->unsignedInteger('created_at'); 
    $table->unsignedInteger('updated_at');
    

    其次,如果您不想为所有模型单独设置$dateFormat,请将其设置在BaseModel 中并让所有模型扩展该类:

    class BaseModel extends Illuminate\Database\Eloquent\Model {
      protected $dateFormat = 'U';
    }
    
    class User extends BaseModel {
      ...
    }
    

    【讨论】:

    • @Aleks 不要在没有说明任何正当理由的情况下投反对票。我们花时间回答您的问题,而您只是投了反对票,甚至不关心说明您反对的原因
    • 很遗憾,不是我。
    • created_at updated_at 列为unsignedInteger 有什么好处?
    • 我在我的情况下尝试过那个,但我们也可以使用整数。
    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多