我有一个名为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使用约束处理此问题感兴趣。我在处理我如何使用它们以及如何实现我正在尝试使用它时遇到一些麻烦。任何帮助表示赞赏。
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不必位于同一个迁移中,您可以稍后添加约束,但不能在表中已经有违反该约束的行。