Has_one without ecto / phoenix / elixir affiliation

Problem

I have a table files, and there are many other tables that create a one-to-one association, for example. userscan avatarand postscan have photo.

Possible Solution

A possible solution would be to create a table users_filesand posts_filesand use has_one :through. However, this looks overwhelming.

The perfect solution

The ideal solution is to define tables like this

users
 - avatar_id

posts
 - photo_id

and parameter with:in has_one, so the circuit looks like this:

schema "users" do
    has_one :avatar, MyApp.FileDb, with: :avatar_id, foreign_key: :id #id is default

end

schema "posts" do
    has_one :photo, MyApp.FileDb, with: :photo_id, foreign_key: :id

end

and you do not need to determine belongs_toon files. Is there a similar mechanism already? What is the standard way to handle this in Phoenix?

+4
2

, belongs_to, , . :

+9

, "--". files , . files "", FK , .

, , FK ( belongs_to), ( has_one). , , . , ( FK), .

, FK , , ( ). , ( , , "" , ).

, Repo.delete(avatar) , . . ( has_one , db).

:

def delete(%__MODULE__{} = avatar) do
  avatar
  |> Repo.preload([:file])
  |> Map.get(:file)
  |> Repo.delete()
  |> case do
    {:ok, _file} -> {:ok, avatar}
    {:error, changeset} -> {:error, changeset}
  end
end

, Doctrine mappedBy inversedBy, ORM/. , Ecto, , .

0
source

Source: https://habr.com/ru/post/1608149/


All Articles