Magento – Programmatically update name of category in specific store

magento-2.1magento2

I have a magento 2 multi store setup (e.g. stores with the id 1 – 3) and I want to update the name of the category with the entity_id 3.

I've tried

$cat = $this->_categoryRepository->get(3, 3);
$cat->setName('Test in Store 3');
$this->_categoryRepository->save($cat);

with $this->_categoryRepository being an implementation of Magento\Catalog\Api\CategoryRepositoryInterface obtained via constructor based dependency injection.

But this just updates the value of the current store. I ran this code inside a cli command and it updated the name attribute of store 1 and not store 3.

The save method in Magento\Catalog\Model\CategoryRepository obtains the store via

$storeId = (int)$this->storeManager->getStore()->getId();

which always yields the current store.

What is the correct way to update a store specific attribute of a category? I know I could directly hack the database or use the resource model, but that would totally defeat the purpose of the repository pattern.

Best Answer

$storeId = (int)$this->storeManager->getStore()->getId(); Category name does have scope of store so repository's save method will work fine when you call this code from admin after switching scope using store scope switcher in admin category form. But instead of using save method of the repository you could
Directly call save on category.