【问题标题】:Phoenix/Ecto - restart identity in seedfilePhoenix/Ecto - 在种子文件中重新启动身份
【发布时间】:2017-04-11 01:16:51
【问题描述】:

在 Phoenix 应用程序中使用种子文件时,如果种子多次运行,是否可以重新启动表的身份?

例如,我目前正在使用以下种子:

PhoenixApp.Repo.delete_all PhoenixApp.Role
PhoenixApp.Repo.insert!(%PhoenixApp.Role{role: "admin"})
PhoenixApp.Repo.insert!(%PhoenixApp.Role{role: "non-admin"})

第一行清除表(这样如果种子运行多次,记录就不会堆积),随后的行创建种子记录。正如您通常所期望的那样,运行此代码一次将使用自动递增的主键“1”和“2”创建两条记录。但是,如果我以后想在表格中添加另一个条目,例如

PhoenixApp.Repo.insert!(%PhoenixApp.Role{role: "superuser"})

行的 ID 现在将是“3”、“4”和“5”,因为没有重新启动标识。

Ecto 是否也有重新启动表标识的命令?我意识到我可以通过 IEx 向我的表中添加其他记录,但如果可能的话,我更愿意重新启动身份。

【问题讨论】:

    标签: phoenix-framework ecto


    【解决方案1】:

    在 PostgreSQL 中,您可以执行 ALTER SEQUENCE <sequence name> RESTART 将序列的值重置为其原始值。 ID 主键的序列名称将为#{table_name}_id_seq。您可以使用Repo.query 运行查询,例如:

    Repo.query("ALTER SEQUENCE comments_id_seq RESTART")
    
    iex(1)> Repo.insert!(%Comment{}).id
    11
    iex(2)> Repo.delete_all(Comment)
    {11, nil}
    iex(3)> Repo.insert!(%Comment{}).id
    12
    iex(4)> Repo.query("ALTER SEQUENCE comments_id_seq RESTART")
    {:ok,
     %Postgrex.Result{columns: nil, command: :alter_sequence, connection_id: 3360,
      num_rows: 0, rows: nil}}
    iex(5)> Repo.insert!(%Comment{}).id
    1
    

    【讨论】:

    • 再次感谢@Dogbert!
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    相关资源
    最近更新 更多