Create nested Category via PHP In a custom plugin, I'm able to easily add a new Category:



$category = new CategoryModel();
$category-&gt;groupId = 1;
$category-&gt;getContent()-&gt;title = $categoryName;
craft()-&gt;categories-&gt;saveCategory($category);


That part works great! But for some reason, I can't figure out how to save a nested category.

I'd imagine it's something like this, but it doesn't seem to be working:

$childCategory = new CategoryModel();
$childCategory-&gt;groupId = 1;
$childCategory-&gt;level = 2;
$childCategory-&gt;parent = $parentCategory-&gt;id;
$childCategory-&gt;getContent()-&gt;title = $childCategoryName;
craft()-&gt;categories-&gt;saveCategory($childCategory);


Unfortunately that code is giving me an error:


  Internal Server Error
  
  Trying to get property of non-object


And if I drop the -&gt;id portion of this line:

$childCategory-&gt;parent = $parentCategory;


... it will save the category, but it won't be nested.

What am I doing wrong?
Assuming $parentCategory is an existing CategoryModel (your error says that $parentCategory is not an object):

$childCategory = new CategoryModel();
$childCategory-&gt;groupId = 1;
$childCategory-&gt;newParentId = $parentCategory-&gt;id;
$childCategory-&gt;getContent()-&gt;title = $childCategoryName;

craft()-&gt;categories-&gt;saveCategory($childCategory);


You can see how Craft does it for it's own categories in CategoriesController->saveCategory() and CategoriesService->saveCategory().