【问题标题】:Preload has_one association in a case insensitive manner以不区分大小写的方式预加载 has_one 关联
【发布时间】:2019-05-15 22:17:45
【问题描述】:

我们目前正在从 Ruby/Rails/MariaDB 迁移到 Elixir/Phoenix/MariaDB,我在 Ecto 中预加载关联时遇到了一个问题,我们在 ActiveRecord 中没有看到。

我们在 Rails 项目中定义了一些具有字符串类型外键的关系(我知道,这不是最佳实践)。例如,一个账户有一个计费方案(在新的 Elixir 项目中定义):

schema "accounts" do
  field(:name, :string)
  field(:email_address, :string)
  field(:active, :boolean)
  field(:billing_model, :string)
  has_one(:billing_plan, BillingPlan, foreign_key: :name, references: :billing_model)
end

schema "billing_plans" do
  field(:name, :string)
  field(:price, :integer)
end

当大小写不匹配时会出现问题,例如,如果帐户将 Pro 存储为 billing_model,但 billing_plans 表将其存储为 pro。当我尝试像这样预加载关联时:Repo.get(Account, 1234) |> Repo.preload(:billing_plan),Ecto 为billing_plan 返回nil。然而,如果案例匹配,Ecto 会按预期返回 billing_plan

我最初的想法是在数据库中修复此问题,以使案例匹配。然而,随着新的例子开始出现,这并没有奏效,我意识到这不是这个关联所独有的问题——我们的模式中有很多这样的关系。这就是为什么我想在更高的级别上解决这个问题,这样它以后就不会回来咬我们了。理想情况下,最好在定义关联时将标志传递给数据库配置或选项。

在此之前有没有人遇到过这个问题,可以提供正确的方向或合理的解决方案?

【问题讨论】:

    标签: elixir mariadb phoenix-framework ecto


    【解决方案1】:

    据我所知,由于大写/小写,您的字符串外键不匹配。

    如果您构建自己的查询而不是进行预加载,我无法测试该案例,但它应该类似于

    (from a in Account, join: b in BillingPlan, where: a.billing_model == 1234 and a.billing_model == b.name, select: %{ a | billing_plan: b}) |> Repo.one()
    

    在执行此操作之前,您应该导入 Ecto.Query。

    我希望它有效。

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多