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):
- Open a connection to MySQL.
- Perform a loop on all the objects.
- Check which property has changed.
- Perform a query with either
UPDATEorINSERT. - 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:
- Open connection
- check for property changes
- perform query
- close connection
If your table has a primary key or unique index, you can use a REPLACE statement with all your data at once:
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.