2011-06-06 15:30
浏览 25


Let's say I have a class method named ->saveAll(). This class tracks the objects that's to be put into the database. (Like what doctrine do)

What's the efficient way to save those objects? This is what I'm thinking right now (I'm going to be using MySQL as an example):

  1. Open a connection to MySQL.
  2. Perform a loop on all the objects.
  3. Check which property has changed.
  4. Perform a query with either UPDATE or INSERT.
  5. When the loop finishes, closes the connection.

Is this the best way to do it? Or is there a better way to do it?

Also, let's say if i want to ->saveOne($object). Would the following be good:

  1. Open connection
  2. check for property changes
  3. perform query
  4. close connection

图片转代码服务由CSDN问答提供 功能建议

假设我有一个名为 - > saveAll()的类方法。 该类跟踪要放入数据库的对象。 (就像学说一样)

保存这些对象的有效方法是什么? 这就是我现在想的(我将以MySQL为例):

  1. 打开与MySQL的连接。 \ n
  2. 对所有对象执行循环。
  3. 检查哪个属性已更改。
  4. 使用 UPDATE 执行查询或 INSERT
  5. 当循环结束时,关闭连接。

    这是最好的方式 做到了吗? 或者有更好的方法吗?

    另外,假设我想要 - > saveOne($ object)。 以下是好的:

    1. 打开连接
    2. 检查属性更改
    3. 执行查询
    4. 关闭连接
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douju7245 2011-06-06 15:48

    If your table has a primary key or unique index, you can use a REPLACE statement with all your data at once:

    REPLACE INTO foo (id, bar) VALUES (NULL, 'baz'), (1, 'hello');

    The row will be inserted if it does not exist or if the primary key/unique index is not specified. If the primary key or unique index is found, it will be updated instead.

    Also, when MySQL executes an UPDATE (or when it updates through REPLACE), it will check each value to see if it has changed automatically (without the need to do it yourself) and leave it as-is if it hasn't, without any extra operation.

    打赏 评论

相关推荐 更多相似问题