الارتباطات والمخططات المضمّنة
تعاملوا مع العلاقات بين نماذج البيانات المختلفة باستخدام ارتباطات Ecto، وضمّنوا البيانات مباشرةً باستخدام المخططات المضمّنة.
الارتباطات والمخططات المضمّنة درس مجاني في Elixir & Phoenix: Scalable Backend Development على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Elixir & Phoenix: Scalable Backend Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Elixir & Phoenix: Scalable Backend Development 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Linking Your Data Together
In relational databases, data is often spread across multiple tables to avoid redundancy and ensure data integrity. Associations in Ecto help you define how these different pieces of data relate to each other.
Think of a blog: A user can write many posts, and each post belongs to one user. Ecto allows you to model these relationships directly in your Elixir schemas.
- Organize related data logically.
- Simplify querying and data retrieval.
- Maintain data consistency.
One User, Many Posts
The most common relationship is one-to-many. For example, one User can have many Posts, but each Post belongs to only one User.
In Ecto, you define this using has_many on the "one" side (e.g., User) and belongs_to on the "many" side (e.g., Post). The belongs_to macro also tells Ecto to add a foreign key (like user_id) to the Post's database table.
Coding `has_many` and `belongs_to`
Let's define our User and Post schemas. Notice how has_many and belongs_to link them. The belongs_to macro expects the name of the association and the module of the associated schema.
defmodule MyApp.User do
use Ecto.Schema
schema "users" do
field :name, :string
has_many :posts, MyApp.Post # A user has many posts
timestamps()
end
end
defmodule MyApp.Post do
use Ecto.Schema
schema "posts" do
field :title, :string
field :content, :string
belongs_to :user, MyApp.User # A post belongs to one user
timestamps()
end
endWorking with Linked Records
Once schemas are defined, you can create records and link them. Ecto allows you to preload associations, fetching related data in a single query to avoid N+1 problems. Here's how you might create a user and posts, then view the user with their posts.
defmodule MyScript do
# Mock schemas for demonstration (assuming they are defined)
defmodule User do
defstruct [:id, :name, :posts]
end
defmodule Post do
defstruct [:id, :title, :content, :user_id]
end
def run do
IO.puts "--- Demonstrating One-to-Many ---"
# Simulate creating a user
user = %User{id: 1, name: "Alice"}
IO.inspect user, label: "Created User"
# Simulate creating posts linked to the user
post1 = %Post{id: 101, title: "My First Post", content: "Hello world!", user_id: user.id}
post2 = %Post{id: 102, title: "Elixir Fun", content: "Learning Elixir!", user_id: user.id}
# In a real app, you'd use Repo.insert! and Repo.preload
# To show the concept of preloading, we manually add posts to the user struct
user_with_posts = %{user | posts: [post1, post2]}
IO.inspect user_with_posts, label: "User with preloaded posts"
end
end
MyScript.run()Multiple Connections: `many_to_many`
Sometimes, records have a many-to-many relationship. For example, a Student can enroll in many Courses, and each Course can have many Students.
Ecto handles this using a join table (or "pivot table"). You define a schema for this intermediate table, and Ecto uses it to manage the connections between the two main schemas with the many_to_many macro.
- Requires a separate join schema.
- Connects two schemas where both sides can have multiple related records.
- Common for tags, roles, or group memberships.
Coding `many_to_many`
Let's define Student and Course schemas, along with a Enrollment join schema. The many_to_many macro is used on both Student and Course, specifying the join schema.
defmodule MyApp.Student do
use Ecto.Schema
schema "students" do
field :name, :string
many_to_many :courses, MyApp.Course, join_through: MyApp.Enrollment
timestamps()
end
end
defmodule MyApp.Course do
use Ecto.Schema
schema "courses" do
field :title, :string
many_to_many :students, MyApp.Student, join_through: MyApp.Enrollment
timestamps()
end
end
defmodule MyApp.Enrollment do
use Ecto.Schema
schema "enrollments" do
# These are foreign keys to Student and Course
belongs_to :student, MyApp.Student
belongs_to :course, MyApp.Course
timestamps()
end
endAccessing Many-to-Many Links
Similar to one-to-many, you use Ecto.Repo.preload/2 to fetch associated many-to-many records. Ecto automatically handles querying the join table behind the scenes.
defmodule MyScript.Many do
# Mock schemas for demonstration
defmodule Student do
defstruct [:id, :name, :courses]
end
defmodule Course do
defstruct [:id, :title, :students]
end
defmodule Enrollment do
defstruct [:id, :student_id, :course_id]
end
def run do
IO.puts "--- Demonstrating Many-to-Many ---"
# Simulate creating a student and courses
student1 = %Student{id: 1, name: "Maria"}
courseA = %Course{id: 101, title: "Elixir Basics"}
courseB = %Course{id: 102, title: "Phoenix Framework"}
# Simulate enrollments (join table entries)
_enrollment1 = %Enrollment{student_id: student1.id, course_id: courseA.id}
_enrollment2 = %Enrollment{student_id: student1.id, course_id: courseB.id}
# Simulate preloading courses for student1
student1_with_courses = %{student1 | courses: [courseA, courseB]}
IO.inspect student1_with_courses, label: "Student with preloaded courses"
end
end
MyScript.Many.run()Data Within Data: Embedded Schemas
While associations link separate records, embedded schemas allow you to store structured data directly within a parent record's field. This means the embedded data is not in a separate table but is part of the parent's row.
Use embedded schemas when the nested data only makes sense in the context of its parent and doesn't need to be independently queried or shared.
- Data stored directly in the parent record.
- No separate database table or foreign keys.
- Ideal for simple, dependent nested data like addresses or metadata.
Coding Embedded Schemas
You define an embedded schema using embeds_one or embeds_many within the parent schema. The embedded schema itself uses Ecto.Schema with @primary_key false and @foreign_key_type :binary_id (or false for no ID) as it's not a standalone table.
defmodule MyScript.Embed do
defmodule Address do
use Ecto.Schema
@primary_key false # Embedded schemas don't have their own primary key
@foreign_key_type :binary_id # Or false if no ID needed at all
schema "addresses" do # Table name is ignored for embeds
field :street, :string
field :city, :string
field :zip_code, :string
end
end
defmodule Profile do
use Ecto.Schema
schema "profiles" do
field :username, :string
embeds_one :address, MyScript.Embed.Address, on_replace: :delete # Embeds one address
timestamps()
end
end
def run do
IO.puts "--- Demonstrating Embedded Schemas ---"
# Create a profile with an embedded address
profile_changeset =
Ecto.Changeset.change(%Profile{}, %{username: "john_doe"})
|> Ecto.Changeset.put_embed(:address, %{
street: "123 Main St",
city: "Anytown",
zip_code: "12345"
})
# In a real app: Repo.insert!(profile_changeset)
# Simulate the resulting struct
profile_with_address = %Profile{
id: 1,
username: "john_doe",
address: %Address{street: "123 Main St", city: "Anytown", zip_code: "12345"}
}
IO.inspect profile_with_address, label: "Profile with embedded address"
end
end
MyScript.Embed.run()Check Your Understanding
You've learned about Ecto associations and embedded schemas. Let's test your knowledge!
Associations & Embeds: Key Takeaways
Great job! You've mastered how to model relationships in Ecto:
- One-to-many: Use
has_manyandbelongs_to. The foreign key lives on thebelongs_toside. - Many-to-many: Use
many_to_manywith a dedicatedjoin_throughschema. - Embedded Schemas: Use
embeds_oneorembeds_manyto store dependent, structured data directly within a parent record. - Always use
Ecto.Repo.preload/2to fetch associated data efficiently.
These powerful features are fundamental to building robust and well-structured Ecto applications. Keep practicing!
الأسئلة الشائعة
هل درس «الارتباطات والمخططات المضمّنة» مجاني؟
نعم — نص درس «الارتباطات والمخططات المضمّنة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Elixir & Phoenix: Scalable Backend Development، انتقل إلى CoddyKit PRO. تتضمن دورة Elixir & Phoenix: Scalable Backend Development 4 دروس في المجموع.
ماذا ستتعلم في «الارتباطات والمخططات المضمّنة»؟
تعاملوا مع العلاقات بين نماذج البيانات المختلفة باستخدام ارتباطات Ecto، وضمّنوا البيانات مباشرةً باستخدام المخططات المضمّنة. تتمرن على Elixir & Phoenix: Scalable Backend Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Elixir & Phoenix: Scalable Backend Development؟
لا تُشترط خبرة سابقة. Elixir & Phoenix: Scalable Backend Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «الارتباطات والمخططات المضمّنة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Elixir & Phoenix: Scalable Backend Development هذا؟
نعم. كل درس في Elixir & Phoenix: Scalable Backend Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- مخطط Ecto وترحيلات قاعدة البيانات
- Repo وChangesets والاستعلامات
- الارتباطات والمخططات المضمّنة
- المعاملات وEcto.Multi