Save a selected category for a user (using a plugin) I have some categories, and with the use of a category field a user can select these from within his / her profile.

Which is shown in the image:



In my Twig template I can get the user selections out using the following code.

{% set property_prefs = craft.categories({
    relatedTo: { sourceElement: currentUser, field: "propertyPreference" },
    limit:     null
}) %}


But what I want to know is how can I programmatically save a user selection using the API from within my plugin.

Also, which table are these stored in?
I had to do something similar to this in a plugin recently, Inserting Relationship Into Entries Field - Plugin Not Saving Relation, I know it's users to an entry field but I would assume the methods are similar.

So you will need 3 things in order to save a users categories

1. The Craft\FieldModel of the field which has the associations

$field = craft()-&gt;fields-&gt;getFieldByHandle('propertyPreference');

2. The source, in this case the matrix block that has the field

$source = craft()-&gt;matrix-&gt;getBlockById(&lt;someId&gt;);

3. An array of element id's you wish to relate to the field

$relations = $user-&gt;propertyPreference-&gt;ids(); 

Once you have those you can edit the $relations array however you see fit and then simply save the relations back

craft()-&gt;relations-&gt;saveRelations($field , $source, $relations);

You can find out more about the save relations function in the class reference

As for which table, I would assume they are in craft_relations