Setting a relationship to null

If i have a business object, that has a has-many relationship, and I want to remove one of those relationships (for example, a product has multiple roles, I want to delete one of those roles from a Product page), how is this done?
If I have a list of Roles, and do a .remove, it actually deletes the Role itself, but I want to just set that particular one to null…

If the has many is truly a “belongs to” in the other direction (a role belongs to a product in your example), deleting the role is the right thing to do. Otherwise you would have orphan roles floating around not connected to any products.

This is more of an exercise, so bear with me :slight_smile:
As am example, let’s say that roles and products are defined independently, so having an orphan role is ok.
The role page can connect to a Product, that’s no problem (system does that for you, with a UI with a select pointing to the productId related to the current product).
And on the product page, we list the roles associated, and want to (orphanize) one.
How could this be done…I assume a script could address the Role that’s attached to the product under edit…but can’t get the syntax of how to delete that productId field from the role

Got it. Let’s assume that your list has a click action to remove the role and that passes the selected role into a method called “disconnectRole” with an input of “roleToUnlink”:

roleToUnlink.productId = null;
await roleToUnlink.save();

const index = this.product.roles.indexOf(roleToRemove);
this.product.roles.splice(index,1);

The first two lines clear the productId and wait for the patch operation to complete.

The last two lines remove the role from the list in memory.

That should do it!

Kirk followed my suggested approach and it did not work :(. Turns out because his list (roles) is an alias of an included array, setting productId to null was ignored. When you bring a list in as a child with an include, the parent id (productId in this case) is sort of “hard coded” for you. That helps when you do something like add but got in the way here. The final solution was to do this:

await Role.updateById(roleToUnlink.id, {productId: null});

const index = this.product.roles.indexOf(roleToRemove);
this.product.roles.splice(index,1);

Thank you for your patience on my incorrect suggestion Kirk!