【问题标题】:Phoenix Ecto ** (Mariaex.Error) (1054): Unknown column 'inserted_at' in 'field list'Phoenix Ecto **(Mariaex.Error)(1054):“字段列表”中的未知列“inserted_at”
【发布时间】:2016-08-09 19:45:07
【问题描述】:

使用 Elixir + Phoenix 将模型插入 MySQL 数据库时,我得到:

** (Mariaex.Error) (1054): Unknown column 'inserted_at' in 'field list'
     stacktrace:
       (ecto) lib/ecto/adapters/mysql.ex:181: Ecto.Adapters.MySQL.insert/5
       (ecto) lib/ecto/repo/schema.ex:381: Ecto.Repo.Schema.apply/4
       (ecto) lib/ecto/repo/schema.ex:185: anonymous fn/11 in Ecto.Repo.Schema.do_insert/4
       (ecto) lib/ecto/repo/schema.ex:595: anonymous fn/3 in Ecto.Repo.Schema.wrap_in_transaction/6
       (ecto) lib/ecto/adapters/sql.ex:472: anonymous fn/3 in Ecto.Adapters.SQL.do_transaction/3
       (db_connection) lib/db_connection.ex:973: DBConnection.transaction_run/4
       (db_connection) lib/db_connection.ex:897: DBConnection.run_begin/3
       (db_connection) lib/db_connection.ex:671: DBConnection.transaction/3

其他型号不会发生这种情况,可以正常工作。 模型架构是:

  schema "accounts" do
    field :key, :string, null: false
    field :cypher_key, :string, null: false
    field :another_key, :string, null: false
    field :another_cypher_key, :string, null: false
    belongs_to :user, MyApp.User
    timestamps()
  end

插入时我正在做:

Repo.insert! %Account{key: "test",
                      cypher_key: "test",
                      another_key: "test",
                      another_cypher_key: "pk_test"
             }

当通过 MySQL cmd 手动插入时,它可以正常工作。

【问题讨论】:

    标签: mysql elixir phoenix-framework


    【解决方案1】:

    您的表是否包含timestamps 字段?您是否为此生成了适当的迁移?

    使用mix ecto.gen.migration,然后打开文件,该文件将在/priv/repo/migrations 中创建。

    将change 函数更改为类似以下内容:

    def change do
      create table(:accounts) do
        add :key, :string
        # etc.
    
        timestamps
      end
    
      create unique_index(:accounts, [:key])
    end
    

    然后使用 mix ecto.migrate 应用此迁移。

    我希望它会有所帮助。

    【讨论】:

      【解决方案2】:

      很可能您没有在迁移文件中添加timestamps。对于Ecto.Schema 和迁移文件,timestamps 函数引用两个字段:updated_at 和inserted_at。如果您碰巧来自 Ruby on Rails,您可能会注意到与 created_at 的命名差异。有关更多详细信息,请参阅the docs here。

      【讨论】:

        猜你喜欢
        • 2020-10-27
        • 2018-10-21
        • 1970-01-01
        • 2021-01-26
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多