Ecto协会自定义名称

时间:2017-11-27 05:49:05

标签: associations elixir ecto

是否可以为关联设置自定义名称?

例如:我有古典"用户 - >帖子"情况:

create table(:users) do
    add :first_name, :string
    add :last_name, :string

    timestamps()
end

create table(:posts) do
    add :text, :string
    add :user_id, references(:users, on_delete: :nothing)

    timestamps()
end

和架构:

schema "users" do
  field :first_name, :string
  field :last_name, :string
  has_many :posts, MyProj.Post

  timestamps()
end

schema "posts" do
  field :text, :string
  belongs_to :user, MyProj.User

  timestamps()
end

我希望posts中的关联不是user而是author。 如果我将架构更改为:

schema "posts" do
  field :text, :string
  belongs_to :author, MyProj.User, [foreign_key: :user_id]

  timestamps()
end

我收到错误:field 'author' in 'select' does not exist in schema MyProj.Post

编辑:

我在尝试查询所有帖子时遇到错误:

def all_posts _root, _args, _info do
  posts_query = from p in Post,
    preload: [:author],
    select: %{
      posted_by: p.author,
      text: p.text
    }

  posts = Repo.all(posts_query)
  {:ok, posts}
end

堆栈追踪:

[info] Sent 500 in 30ms
[error] #PID<0.478.0> running MyProj.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /graphiql
** (exit) an exception was raised:
    ** (Ecto.QueryError) lib/my-proj/resolvers/post_resolver.ex:7: field `author` in `select` does not exist in schema MyProj.Post in query:

from p in MyProj.Post,
  select: %{posted_by: p.author, text: p.text},
  preload: [:author]

        (ecto) lib/ecto/repo/queryable.ex:124: Ecto.Repo.Queryable.execute/5
        (ecto) lib/ecto/repo/queryable.ex:37: Ecto.Repo.Queryable.all/4
        (my-proj) lib/my-proj/resolvers/post_resolver.ex:17: MyProj.PostResolver.all_posts/3
        (absinthe) lib/absinthe/resolution.ex:147: Absinthe.Resolution.call/2
        (absinthe) lib/absinthe/phase/document/execution/resolution.ex:191: Absinthe.Phase.Document.Execution.Resolution.reduce_resolution/1
        (absinthe) lib/absinthe/phase/document/execution/resolution.ex:161: Absinthe.Phase.Document.Execution.Resolution.do_resolve_field/4
        (absinthe) lib/absinthe/phase/document/execution/resolution.ex:147: Absinthe.Phase.Document.Execution.Resolution.do_resolve_fields/6
        (absinthe) lib/absinthe/phase/document/execution/resolution.ex:87: Absinthe.Phase.Document.Execution.Resolution.walk_result/5
        (absinthe) lib/absinthe/phase/document/execution/resolution.ex:57: Absinthe.Phase.Document.Execution.Resolution.perform_resolution/3
        (absinthe) lib/absinthe/phase/document/execution/resolution.ex:25: Absinthe.Phase.Document.Execution.Resolution.resolve_current/3
        (absinthe) lib/absinthe/pipeline.ex:247: Absinthe.Pipeline.run_phase/3

1 个答案:

答案 0 :(得分:0)

问题不在于协会的名称,而在于我误解了Ecto如何解释查询。

由于查询中的实体是“DB table”行,而是

中的模式结构实体
select: %{
  posted_by: p.author,
  text: p.text
}

Ecto正在尝试查找名为host的表列,该列不存在。 为了“修复”这个查询,我需要以更“SQL-ish”的方式思考它:

posts_query = from p in Post,
join: author in assoc(p, :author),
select: %{
  posted_by: author,
  text: p.text
}