逆多态与外部 [英] Inverse polymorphic with ecto

查看:70
本文介绍了逆多态与外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前的Ecto文档 http://hexdocs.pm/ecto/Ecto.Schema.html 仅说明了当多态Comment可以同时属于TaskPost时,如何建立belongs_to类型的多态关联.但是相反的方向呢?

the current Ecto documentation http://hexdocs.pm/ecto/Ecto.Schema.html only explains how to build a belongs_to type of polymorphic association, when the polymorphic Comment can belong to both Task and Post. But what about opposite direction?

例如,有一个Listing,它可以具有四种类型之一的属性:RoomApartmentVilaOffice.

For example there is a Listing which can have a one of the four types of properties: Room, Apartment, Vila or Office.

考虑一对一的关系,在上面的示例中,这意味着应该存在rooms_listingsapartments_listingsvila_listingsoffice_listings,这是不可能的,因为这将导致重复与listings相关的所有其他表.

Considering a one-to-one relationship, given the example above it would mean that there should be rooms_listings, apartments_listings, vila_listings and office_listings, which is impossible, because that will lead to the duplication of all of the other tables associated with listings.

问题是如何建立这种关系的模型?

The question is how to model this kind of relationship?

推荐答案

我认为最简单的建模方法是翻转关联的两侧,然后将room_id等字段添加到表格:

I think the simplest way to model this is by flipping around the sides of the association and then just adding the room_id, etc. fields to the listings table:

defmodule Listing do
  use Ecto.Model
  schema "listings" do
    belongs_to :room, Room
    belongs_to :apartment, Apartment
    belongs_to :villa, Villa
    belongs_to :office, Office
  end
end

然后,您可以在其他每个表上定义一个has_one :listing关系:

Then you can define a has_one :listing relationship on every one of the other tables:

defmodule Room do
  use Ecto.Model
  schema "rooms" do
    has_one :listing, Listing
  end
end

defmodule Apartment do
  use Ecto.Model
  schema "apartments" do
    has_one :listing, Listing
  end
end

defmodule Villa do
  use Ecto.Model
  schema "villas" do
    has_one :listing, Listing
  end
end

defmodule Office do
  use Ecto.Model
  schema "offices" do
    has_one :listing, Listing
  end
end

这篇关于逆多态与外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆