How do I edit an existing object in the database? For example, if I have a model like this:
class Topic{title,content,author}, when I edit and save the object I do not want to add the “author” object again. How do I update my existing object rather than adding a new one?
How do I edit an existing object in the database? For example, if I
Share
If you’re inheriting from the Model class (as you should), it provides a
save()method as well as an ID attribute. When you callsave()on an object you got out of the database, it will be updated, and if you call it on a new object it will be saved to the database. It’s all automagical!Updating only specific fields
Model.save()saves the whole object, so if you want to update only some data fields in your object, you first have to construct the exact object you want to go in your database. So let’s say you don’t want to update null fields, using yourTopic(id, content, author)object:That’s how I would do it. Depending on how many fields you have this code is going to get really clunky really fast. Definitely put it in a method. Also, see here about findByID() and other ways to pull objects from the database.