【问题标题】:Ecto schema belongs_to association using two fields使用两个字段的 Ecto schema belongs_to 关联
【发布时间】:2022-01-25 05:17:57
【问题描述】:

我有两个模型:AuctionArtwork。一个Artworkbelongs_to 一个Auction

这是针对外部数据库设置的,因此 Ecto 不处理迁移,并且字段在基础数据库中采用驼峰式命名。

我遇到的问题是关联是通过两个字段(元组关联)完成的:token_idcontract_address

token_idcontract_address 都不是唯一的,但是作为一个元组它们是唯一的。

这是Auction 架构:

@primary_key {:auction_id, :id, source: :auctionId}
schema "auction" do
  field :token_id, :integer, source: :tokenId
  field :contract_address, :string, source: :contractAddress
  
  # ideally would want to do something like this
  belongs_to :artwork, Foundation.Artworks.Artwork,
    references: [:contract_address, :token_id]

end

然后是Artwork 架构:

@primary_key {:id, :binary_id, []}
schema "artwork" do
  field :name, :string
  field :description, :string
  field :token_id, :integer, source: :tokenId
  field :contract_address, :string, source: :contractAddress
end

我怎样才能做到这一点,以便 Artwork 使用这两个字段关联?

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

    它对你有用吗:

    @primary_key false
    schema "artwork" do
      field :name, :string
      field :description, :string
      field :token_id, :integer, source: :tokenId, primary_key: true
      field :contract_address, :string, source: :contractAddress, primary_key: true
    end
    

    【讨论】:

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