config :friends, Friends.Repo, database: "friends_repo", username: "user", password: "pass", hostname: "localhost"
defmodule Friends.Repo.Migrations.CreatePeople do use Ecto.Migration def change do create table(:people) do add :first_name, :string add :last_name, :string add :age, :integer end end end
建立數據庫裏的表結構:mix ecto.migratehtml
若是以爲剛纔的表結構有問題,回滾:mix ecto.rollback數據庫
defmodule Friends.Person do use Ecto.Schema schema "people" do field :first_name, :string field :last_name, :string field :age, :integer end end
在iex裏:person = %Friends.Person{} 或者person = %Friends.Person{age: 28} 建立一個新的struct。能夠用schema和數據庫進行交互。如Repo.insert!(person),會返回他的id(主鍵)注意:不加!會出錯。 eg2: Repo.delete!(person) 刪除剛纔的記錄數據結構
def changeset(user, params \\ %{}) do user |> cast(params, [:name, :email, :age]) |> validate_required([:name, :email]) |> validate_format(:email, ~r/@/) |> validate_inclusion(:age, 18..100) end
cast function裏:會返回一個 changeset, 所列的參數是後面要用到的(validate)。app
has_manypost
belongs_toui
在使用時,能夠用preload,有三種用法spa
Repo.all from p in Post, preload: [:comments]
Repo.all from p in Post, join: c in assoc(p, :comments), where: c.votes > p.votes, preload: [comments: c]
posts = Repo.all(Post) |> Repo.preload(:comments)
Ecto模塊也提供一些方法如: Ecto.assoc/2
returns a query with all associated data to a given struct:code
import Ecto # Get all comments for the given post Repo.all assoc(post, :comments) # Or build a query on top of the associated comments query = from c in assoc(post, :comments), where: not is_nil(c.title) Repo.all(query)
build_assoc/3
, which allows someone to build an associated struct with the proper fields:orm
詳情查看官方文檔。htm
注意一點:Ecto 要使用ecto.create
and ecto.migrate,必須先定義
:ecto_repos:
config :my_app, :ecto_repos, [MyApp.Repo] config :my_app, MyApp.Repo, database: "ecto_simple", username: "postgres", password: "postgres", hostname: "localhost"
1.插入記錄:
person = %Friends.Person{}
Friends.Repo.insert(person)
2.對記錄進行校對:
def changeset(person, params \\ %{}) do person |> Ecto.Changeset.cast(params, [:first_name, :last_name, :age]) |> Ecto.Changeset.validate_required([:first_name, :last_name]) end
person = %Friends.Person{}
changeset = Friends.Person.changeset(person, %{})
Friends.Repo.insert(changeset)
changeset.valid? 可判斷校對正確與否
3.查詢第一條記錄
Friends.Person |> Ecto.Query.first |> Friends.Repo.one
4.查詢全部記錄
Friends.Person |> Friends.Repo.all
5.根據id獲取記錄
Friends.Person |> Friends.Repo.get(1)
6.根據屬性獲取記錄
Friends.Person |> Friends.Repo.get_by(first_name: "Ryan")
Friends.Person |> Ecto.Query.where(last_name: "Smith") |> Friends.Repo.all
7.從查詢的記錄中查詢
query = Friends.Person |> Ecto.Query.where(last_name: "Smith")
query = query |> Ecto.Query.where(first_name: "Jane")
8.update記錄
person = Friends.Person |> Ecto.Query.first |> Friends.Repo.one
changeset = Friends.Person.changeset(person, %{age: 29})
Friends.Repo.update(changeset)
9.刪除記錄
person = Friends.Repo.get(Friends.Person, 1)
Friends.Repo.delete(person)