How to handle 'related' categories within import script So I'm attempting to hack together a script to import thousands of entries and hundreds of categories from a bespoke system.

I have imported all the categories (around 800 of them) successfully. The category group they've been imported into has a 'relatedCategories' field so that each category can optionally be related to other categories in the group.

I'm now looking to do a second pass to import the related categories,  this is the part I can't quite get my head round.

The story so far...

    $db = new DbConnection(***);
    $db-&gt;charset = 'utf8';

    $entries = $db-&gt;createCommand()
        -&gt;setText('SELECT * FROM categories')
        -&gt;queryAll();

    foreach ($entries as $entry)
    {
        $craftcat_criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
        $craftcat_criteria-&gt;title = $entry['title'];
        $craftcat = $craftcat_criteria-&gt;first();

        $related_array = array_filter(explode('#',$entry['similar']));

        $relatedcats = [];

        foreach ($related_array as $related_item)
        {
            $related_criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
            $related_criteria-&gt;title = $related_item;

            $related_cat = $related_criteria-&gt;first();

            $relatedcats[] = $related_cat-&gt;id;
        }
    }


So I have the ElementCriteriaModel for the category and an array containing the ID of each of the related categories.

I'm going on the basis that it's craft()-&gt;relations-&gt;saveRelations() I need to use, but I just can't get the syntax right.

Can someone give me a shove in the right direction?
Sorted. This seems to work...

$catFieldRecord = FieldRecord::model()-&gt;findById(4);
$catFieldModel = FieldModel::populateModel($catFieldRecord);

craft()-&gt;relations-&gt;saveRelations($catFieldModel, $craftcat, $relatedcats);