教义:如何仅保存数据库中尚不存在的集合项
我有一个项目集合要保存到数据库中,但我希望仅在不存在时才插入记录。
我认为最有效的方法是在保存之前过滤集合。 Doctrine能自动做到吗?
或者我应该获取集合中所有项目的所有 id,然后查询数据库以查找这些 id 列表中不存在的项目,然后在 foreach 中删除我们不需要的所有集合项目,最后保存集合?
有更好的方法建议吗?
I have a collection of items to save to database, but I want the record to be inserted only if not exists.
I think the most effective way would be to filter the collection before saving. Can Doctrine do it automatically?
Or shall I get all id's of all items in the collection, then query the database for items which do not exists on the list of these id's, then in foreach remove all collection items which we do not need, and finally save collection?
Any better approach suggested?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Doctrine_Collection 类中的保存函数,
我不确定您从哪里获取集合,或者您是否手动构建它,但您可能想尝试扩展 Doctrine_Collection 类并重载保存函数,如下所示
This is the save function from the Doctrine_Collection class
I'm not sure where you are getting your collection from, or if you are manually building it, but you might want to try extending the Doctrine_Collection class and overloading the save function like this
我对 Doctrine 一无所知,但是 MySQL REPLACE 查询正是您想要的 - 更新现有行和更新现有行。如果未找到主键匹配,则创建新行。
I don't know anything about Doctrine, but the MySQL REPLACE query does just what you want - updates existing rows & creates new rows if no primary key matches were found.