将PHP对象加载/保存到MySQL数据库

I have an object for a „listing“, which has attributes like id, name, description, etc. which can be loaded via load($id) method.

It has some advanced attributes, too. For example multiple products (which is a separate object). To improve performance, I load them when you try to access them with listing->getProducts().

Now I want a save method in listing, to save the values back to the MySQL db. But I‘m not sure how to do that product saving in a clean way. The best way would be adding a save method to products object and call it from the listing object, but that only saves the values. How do I handle added/removed products? That has to be done by the listing object I think. But how do I know if all products were removed or if they weren't even loaded (because they didn’t get accessed)?

All ways, like storing a boolean loaded products seem like a stupid solution. Do you have a good idea how to handle that? I‘m not inexperienced in coding but I want to improve my structure since I always end in a lot of code mess if projects get bigger.

I assume we are talking about adding, editing, and deleting products in your database. So you are probably going to need an 'insert' method and a 'delete' method (invoked from your list view). as well as the 'save' (update) method.

But the problem, or so I understand, is that you don't know which of these to use on a particular product line.

If you are just allowing the user to type willy nilly into input fields, so that you can't tell whether this is an edit, an insert, or a delete (or indeed which product you are editing or deleting, if you allow /every/ field to be changed) then you are making your life really complicated - is this necessary, from a business requirement/UI design perspective?

Consider something like listing the existing information read only and providing edit/insert/delete buttons.

I think I found a more or less good way on my own.

For the first problem (where to save what): Storing of basic attributes of listing in the listing->save() method, calling listing->products[]->save() to store products details, syncing the listing<->product associations in listing->save().

Second problem (Deleting products, just because they didn't got load): That was pretty easy, listing->products = null -> not loaded, listing->products = array() -> loaded, but empty. (I should got this earlier, haha)