gpt4 book ai didi

elixir - 如何自定义 Phoenix id

转载 作者:行者123 更新时间:2023-12-04 06:16:46 25 4
gpt4 key购买 nike

使用 Phoenix 框架,:id, :integer会自动生成。
http://www.phoenixframework.org/docs/ecto-custom-primary-keys

但我不希望它自动生成并使用自定义 id 字段,例如 :id, :string ,很像这样
http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/

要设置

defmodule MyApp.Item do
use MyApp.Web, :model

# @primary_key {:id, :id, autogenerate: false}
schema "items" do
field :id, :string, autogenerate: false # some unique id string
field :type, :integer

它引发 ** (ArgumentError) field/association :id is already set on schema https://github.com/elixir-lang/ecto/blob/db1f9ccdcc01f5abffcab0b5e0732eeecd93aa19/lib/ecto/schema.ex#L1327

最佳答案

我面临两个问题。

  • 两者 @primary_key {:id, :id, autogenerate: false}fields :id子句不能在架构定义中。

  • 这是解决方案

    defmodule MyApp.Item do
    use MyApp.Web, :model

    @primary_key {:id, :string, []}
    schema "items" do
    # field :id, :string <- no need!
  • 为了避免自动生成的 id,我只需要编辑迁移文件

  • 像这样

    defmodule MyApp.Repo.Migrations.CreateItem do
    use Ecto.Migration

    def change do
    create table(:items, primary_key: false) do
    add :id, :string, primary_key: true

    最后,我可以执行 mix ecto.migrate并且可以得到下面的表定义

    mysql> SHOW CREATE TABLE items;
    | items | CREATE TABLE `builds` (
    `id` varchar(255) NOT NULL,

    官方文件肯定是这样说的
    http://www.phoenixframework.org/docs/ecto-custom-primary-keys

    Let's take a look at the migration first, priv/repo/migrations/20150908003815_create_player.exs. We'll need to do two things. The first is to pass in a second argument - primary_key: false to the table/2 function so that it won't create a primary_key. Then we'll need to pass primary_key: true to the add/3 function for the name field to signal that it will be the primary_key instead.



    但是一开始,你不想要列 id ,你只要做 create table(:items, primary_key: false)在迁移中,并编辑架构

    defmodule MyApp.Item do
    use MyApp.Web, :model

    # @primary_key {:id, :string, []}
    @primary_key false # to avoid unnecessary IO scanning
    schema "items" do
    # field :id, :string <- no need!

    虽然自行解决,但还是谢谢

    关于elixir - 如何自定义 Phoenix id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35447042/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com