0Pricing
Elixir & Phoenix: Scalable Backend Development · 课时

Ecto 模式与数据库迁移

定义 Ecto 模式,将 Elixir 结构体映射到数据库表,并使用迁移管理模式变更。

Ecto 模式与数据库迁移 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Elixir & Phoenix: Scalable Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Ecto?

Welcome to Ecto! It's Elixir's powerful toolkit for interacting with databases. Think of it as your bridge between Elixir data and your database.

Ecto isn't a traditional Object-Relational Mapper (ORM). Instead, it's a data mapper. This means it focuses on mapping data between your Elixir application (using structs) and your database tables, giving you more control and less 'magic'.

Elixir Structs: Data Shapes

Before Ecto maps data to a database, Elixir uses structs to define data shapes. A struct is a special kind of map that ensures a predefined set of keys and default values.

Ecto schemas build upon this idea, extending structs to understand how their fields correspond to database columns.

Try running this simple struct example:

defmodule UserData do
  defstruct name: "", age: 0, email: ""
end

# Create struct instances
user1 = %UserData{name: "Alice", age: 30}
user2 = %UserData{email: "bob@example.com"}

IO.puts "User 1: #{inspect user1}"
IO.puts "User 2: #{inspect user2}"
IO.puts "User 1's age: #{user1.age}"

Defining an Ecto Schema

An Ecto schema is an Elixir module that describes how an Elixir struct maps to a database table. It defines the fields, their types, and any special options.

Here's how you'd define a basic User schema, mapping to a users table in your database:

defmodule MyApp.User do
  use Ecto.Schema

  schema "users" do
    field :name, :string
    field :email, :string
    field :age, :integer

    timestamps()
  end
end

Common Schema Field Types

When defining fields in your schema, you specify their type. Ecto provides many common types that map directly to database types:

  • :string: For text data (e.g., names, emails).
  • :integer: For whole numbers.
  • :float or :decimal: For numbers with decimal points.
  • :boolean: For true/false values.
  • :datetime or :naive_datetime: For date and time values.
  • :binary: For raw binary data.

Choosing the right type helps Ecto validate data and create appropriate database columns.

Primary Keys & Timestamps

Ecto schemas automatically include a primary key, usually an id column of type :integer. You don't need to define it explicitly.

The timestamps() macro is super handy! It automatically adds two fields to your schema and database table:

  • :inserted_at: Stores when the record was created.
  • :updated_at: Stores when the record was last modified.

These fields are crucial for tracking changes and are automatically managed by Ecto.

Introducing Database Migrations

Your Ecto schemas define the *desired* structure of your database. But how do you apply these changes to the actual database?

This is where migrations come in! A migration is an Elixir script that describes changes to your database schema, like creating tables, adding columns, or changing types. They ensure your database schema evolves in a controlled, versioned way.

Generating a Migration File

You create new migration files using the Mix command mix ecto.gen.migration. You provide a descriptive name for the migration:

mix ecto.gen.migration create_users_table

This command will generate a new Elixir file in your priv/repo/migrations directory. The filename will include a timestamp, ensuring migrations are applied in the correct order.

Anatomy of a Migration

A migration file contains an Elixir module with a change/0 function. Inside this function, you define your database operations. For example, creating a table:

defmodule MyApp.Repo.Migrations.CreateUsersTable do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :name, :string, null: false
      add :email, :string, null: false
      add :age, :integer

      timestamps()
    end

    create unique_index(:users, [:email])
  end
end

Running Your Migrations

Once you've defined your migrations, you apply them to your database using another Mix command:

mix ecto.migrate

Ecto keeps track of which migrations have been run. If you need to undo the last migration, you can use mix ecto.rollback.

Always run migrations in your development environment first to catch any issues!

Schema vs. Migration

Let's check your understanding of Ecto schemas and migrations.

Recap: Schemas & Migrations

You've taken the first step into Ecto!

  • We learned that Ecto schemas define how Elixir structs map to database tables, specifying fields and types.
  • We explored how migrations are versioned scripts that apply these schema changes to your actual database.
  • You now know how to define a basic schema, generate migration files, and apply them using Mix commands.

Next, we'll dive deeper into interacting with your database using Ecto.Repo and ensuring data integrity with Changesets.

常见问题解答

「Ecto 模式与数据库迁移」课时是免费的吗?

是的 — 「Ecto 模式与数据库迁移」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。

「Ecto 模式与数据库迁移」这节课中我会学到什么?

定义 Ecto 模式,将 Elixir 结构体映射到数据库表,并使用迁移管理模式变更。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Elixir & Phoenix: Scalable Backend Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Elixir & Phoenix: Scalable Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「Ecto 模式与数据库迁移」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Elixir & Phoenix: Scalable Backend Development 课中编写并运行代码吗?

能。每节 Elixir & Phoenix: Scalable Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Ecto 模式与数据库迁移
  2. Repo、Changesets 与查询
  3. 关联与嵌入式模式
  4. 事务与 Ecto.Multi
← 返回 Elixir & Phoenix: Scalable Backend Development