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->charset = 'utf8';

    $entries = $db->createCommand()
        ->setText('SELECT * FROM categories')

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

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

        $relatedcats = [];

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

            $related_cat = $related_criteria->first();

            $relatedcats[] = $related_cat->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()->relations->saveRelations() I need to use, but I just can't get the syntax right.

Can someone give me a shove in the right direction?

1 Answer 1


Sorted. This seems to work...

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.