les*_*ess 4 elixir ecto phoenix-framework
当前的Ecto文档http://hexdocs.pm/ecto/Ecto.Schema.html仅解释了如何构建一种belongs_to多态关联,当多态Comment可以同时属于Task和Post.但相反的方向呢?
例如有一种Listing可以具有四种类型的属性的一个:Room,Apartment,Vila或Office.
考虑到一比一的关系,因为上面的例子那岂不是应该有rooms_listings,apartments_listings,vila_listings和office_listings,这是不可能的,因为这将导致所有相关联的其他表的复制listings.
问题是如何模拟这种关系?
我认为最简单的建模方法是通过翻转关联的两侧,然后只是将room_id等字段添加到listings表中:
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
Run Code Online (Sandbox Code Playgroud)
然后,您可以has_one :listing在其他每个表上定义关系:
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
Run Code Online (Sandbox Code Playgroud)