Elixir Ecto连接到现有的DB



在下面的链接中进行了一些研究

https://github.com/elixir-lang/ecto/tree/master/master/examples/simple

我对如何在长生不老药中使用ecto有些困惑。

总是声明的模式如

defmodule Weather do
  use Ecto.Model
  schema "weather" do
    field :city, :string
    field :temp_lo, :integer
    field :temp_hi, :integer
    field :prcp, :float, default: 0.0
    timestamps
  end
end

,然后在"查询"部分

 def sample_query do
   query = from w in Weather,
      where: w.prcp > 0.0 or is_nil(w.prcp),
      select: w
   Simple.Repo.all(query)
   end
 end

ecto gona使用在天气中声明的架构

我的问题是我只想连接到现有的数据库'testDB'并进行一些选择,我不需要任何新的Schmema来完成我的工作。可以用ecto做到吗?

当我创建自己的查询时,例如

query = from w in tenant

输入命令$ mix do deps.get, compile

错误告诉我function tenant/0 undefined

tenant不起作用,它只是我没有声明的 TESTDB中的一个表

我想我只是迷失了自己的

您可以通过传递字符串来查询数据库中的任何表:

from p in "posts", where: p.id > 0

在这种情况下,您无需定义任何模式,您只需直接查询表即可。最后,您也可以直接进行SQL查询:

Ecto.Adapters.SQL.query(YourRepo, "SELECT $1", [1])

,但随后您将失去大部分好处Ecto给您带来的好处。

您是否需要使用Ecto创建表格的架构。我认为目前没有一个可以自动执行此操作的选项。因此,例如,您可以拥有类似的东西:

defmodule Tenant do
  use Ecto.Model
  schema "tenant" do
    field :id, :integer
    field :name, :string
    # and so on depending on the columns in your table
  end
end

然后做query = from w in Tenant, select: w

最新更新