更新时间:2022-12-02 19:35:04
有两种方法可以实现。其中之一需要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.