代码之家  ›  专栏  ›  技术社区  ›  script

在虚拟表中添加关系

  •  0
  • script  · 技术社区  · 8 年前

    persisting in the database . 我用它们来测试一个库:

    defmodule TestModel.Join do
      @moduledoc false
      use Ecto.Schema
      import Ecto.Changeset
    
      @fields [:public_name, :personal_name, :pass]
      @primary_key false
    
     schema "" do
      field(:public_name, :string, virtual: true)
      field(:pass, :integer, virtual: true)
      field(:personal_name, :string, virtual: true)
      belongs_to(:where, TestModel.Where, define_field: false, foreign_key: :first_name)
     end
    
     def changeset(data) when is_map(data) do
      %__MODULE__{}
      |> cast(data, @fields)
      |> apply_changes()
     end
    end
    

    “属于”关系工作正常,但我还需要在where表中添加许多关系

    defmodule TestModel.Where do
      @moduledoc false
      use Ecto.Schema
      import Ecto.Changeset
    
      @fields [:first_name, :last_name, :personal_id]
      @primary_key false
    
      schema "" do
        field(:first_name, :string, virtual: true)
        field(:personal_id, :integer, virtual: true)
        field(:last_name, :string, virtual: true)
      end
    
     def changeset(data) when is_map(data) do
       %__MODULE__{}
       |> cast(data, @fields)
       |> apply_changes()
     end
    end
    

    如何添加 has_many relation

    这行不通:

    has_many(:joins, TestModel.Join)
    

    1 回复  |  直到 8 年前
        1
  •  0
  •   Aleksei Matiushkin    8 年前

    你有问题 belongs_to 首先。 foreign_key 应该 specify the key in this table ,而不是引用的。那么 has_many

    # in Join schema
    belongs_to(:where, TestModel.Where, foreign_key: :where_id)
    
    # in Where schema
    has_many(:joins, TestModel.Join, foreign_key: :where_id)
    

    如果所属表中没有外键,就不能有一对多关系。