4

在下面的链接中做了一些研究之后

https://github.com/elixir-lang/ecto/tree/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 使用 Wea​​ther中声明的模式形成查询

我的问题是我只想连接到现有数据库“TESTDB”并进行一些 SELECT,我不需要任何新的 schmema 来完成我的工作。请问可以在ecto中做吗?

当我创建自己的查询时

query = from w in tenant

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

错误告诉我function tenant/0 undefined

tenant不是函数,它只是一个TESTDB我没有在任何地方声明的表

我想我只是在ecto中迷失了自己

4

2 回答 2

11

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

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

在这种情况下,您不需要定义任何模式,您可以直接查询表。最后,你也可以直接做一个 SQL 查询:

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

但是,您会失去 Ecto 为您提供的大部分好处。

于 2015-05-11T19:53:22.953 回答
6

无论您是否使用创建表,都需要为表声明架构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

于 2015-05-11T10:47:46.083 回答