如何使用Ecto.Migration约束仅强制执行一个字段

问题描述 投票:0回答:1

我有一个名为Accounts的表,必须有一个“拥有”它的用户或组织。我想强制执行一个约束,强制提供了EITHER user_id或organization_id,但不是两者都没有。该表如下所示:

  def change do
    create table(:accounts, primary_key: false) do
      add(:id, :binary_id, primary_key: true)
      add(:user_id, references(:users, type: :binary_id), null: true)
      add(:organization_id, references(:organizations, type: :binary_id), null: true)

      timestamps()
    end

我可以在变更集中轻松完成此操作,但我对如何使用Ecto.Migration.constraint使用约束处理此问题感兴趣。我在处理我如何使用它们以及如何实现我正在尝试使用它时遇到一些麻烦。任何帮助表示赞赏。

elixir ecto
1个回答
2
投票
  def change do
    # create table

    create constraint(:accounts, :user_or_organization, check: "((organization_id is not null and user_id is null) or (organization_id is null and user_id is not null))")
  end

引用here的解决方案,这就是如何将其应用于Ecto Migrations。请注意,create table和constraint不必位于同一个迁移中,您可以稍后添加约束,但不能在表中已经有违反该约束的行。

© www.soinside.com 2019 - 2024. All rights reserved.