问题描述
假设我有两个模型:父母和孩子。
如果更新了子记录,是否可以自动更新相关的父记录时间戳?
Suppose I have two models: Parent and Child.If a Child record is updated, is there an option to update the associated Parent record timestamp automatically?
推荐答案
有两种方法可以实现。其中之一需要Ecto master(即将成为Ecto v2.0),并且只需直接更新父代即可。
There are a couple ways you can do it. One of them requires Ecto master (soon to be Ecto v2.0) and is by simply updating the parent directly:
# Assuming a child_changeset with the parent loaded
child_changset = Ecto.Changeset.put_assoc(child_changeset, :parent, %{updated_at: Ecto.DateTime.utc})
现在,当孩子坚持下来时,它将自动将更改传播给父级。
Now, when the child is persisted, it will automatically propagate changes to the parent.
或者,您可以使用Ecto v1.1,带有prepare_changes和update_all以传播更改:
Alternatively, you can use Ecto v1.1 with prepare_changes and update_all to propagate the changes:
# Assuming a child_changeset
Ecto.Changeset.prepare_changes child_changeset, fn changeset ->
query = Ecto.assoc(changeset.model, :parent)
changeset.repo.update_all query, set: [updated_at: ^Ecto.DateTime.utc]
changeset
end
在此示例中,我们使用在事务中执行的prepare_changes以及子更改来构建代表父模型的查询,并发出update_all更新与查询匹配的模块的所有updated_at列。
In this example, we use the prepare_changes that is executed in a transaction alongside the child changes to build a query that represents the parent model and issue an update_all updating all updated_at columns for the modules matching the query.
这篇关于自动更新父记录的updated_at字段(Elixir-Ecto)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!