| | 194 | </code> |
| | 195 | |
| | 196 | +++ Replacing records |
| | 197 | |
| | 198 | Replacing records is simple. If you instantiate a new object and save it and then late instantiate another new object with the same primary key or unique index value which already exists in the database, then it will replace/update that row in the database instead of inserting a new one. Below is an example. |
| | 199 | |
| | 200 | First, imagine a User model where username is a unique index. |
| | 201 | |
| | 202 | <code type="php"> |
| | 203 | $user = new User(); |
| | 204 | $user->username = 'jwage'; |
| | 205 | $user->password = 'changeme'; |
| | 206 | $user->save(); |
| | 207 | |
| | 208 | // Issues the following query |
| | 209 | // INSERT INTO user (username, password) VALUES (?,?) ('jwage', 'changeme') |
| | 210 | </code> |
| | 211 | |
| | 212 | Now lets create another new object and set the same username but a different password. |
| | 213 | |
| | 214 | <code type="php"> |
| | 215 | $user = new User(); |
| | 216 | $user->username = 'jwage'; |
| | 217 | $user->password = 'newpassword'; |
| | 218 | $user->replace(); |
| | 219 | |
| | 220 | // Issues the following query |
| | 221 | // REPLACE INTO user (id,username,password) VALUES (?,?,?) (null, 'jwage', 'newpassword') |
| | 222 | // The record is replaced/updated instead of a new one being inserted |