关联 belongs_to 和定义模式时添加字段 id 之间的区别?

The different between association belongs_to and add field id when define a schema?

声明关系有什么不同?

schema "messages" do
    field :user_id, :id
end

schema "messages" do
    belongs_to :user, User
end

当你这样做 field :user_id, :id 时,你实际上并不是在宣告一段关系。您只是添加名为 user_id 的字段,类型为 id.

Belongs_to实际上是添加关系,默认假设外键是user_id。 (这可以通过 foreign_key 选项更改)。
通过使用 belongs_to,Ecto 知道在进行预加载等操作时如何处理相关记录,如何 create/update 附加相关用户,如何级联删除等