【发布时间】:2016-08-22 12:09:02
【问题描述】:
我对 Phoenix-Elixir 很陌生,我想在控制器中进行 mysql 查询。
mysql-query: select * from students where first_name = "abc";
【问题讨论】:
-
询问问题时,如果您提供详细信息,这有助于我们为您提供更好的答案。
我对 Phoenix-Elixir 很陌生,我想在控制器中进行 mysql 查询。
mysql-query: select * from students where first_name = "abc";
【问题讨论】:
假设您正在使用ecto 和mariax,您可以使用Ecto.Query 模块中提供的功能从任何地方进行查询。 from/2 宏已在 web.ex 中为您导入。
def index(conn, params) do
query = from u in MyApp.User,
order_by: u.name
users = Repo.all(query)
end
对于更复杂的查询,您可能希望将查询(但不是对 Repo.all 的调用,如 Should I use Ecto.Repo in Controller or Model for Elixir Phoenix? 中所述)移动到您的模型中。
【讨论】:
Repo 应该是 Chatty.Repo 在 iex 中默认不会被别名。您可以alias Chatty.Repo 然后Repo 将工作。
MyApp.Repo.all(
from s in MyApp.Students,
where: s.first_name == "Mary",
select s
)
【讨论】: