TransWikia.com

Magento 2: What's the difference between Store and Group?

Magento Asked on December 6, 2021

I want to create a Store programatically, but if it already exists, then return the existing store. So far my code looks like this:

private function _getStore($website, $storeName, $storeCode)
{
    try {
        if ($store = $this->storeRepository->get($storeCode)) {
            $groupId = $store->getStoreGroupId();
            return $this->groupRepository->get($groupId);
        }
    } catch (Exception $e) {}

    if ($website->getId() && !empty($storeName) && !empty($storeCode)) {
        /** @var MagentoStoreModelGroup $group */
        $group = $this->groupFactory->create();
        $group->setWebsiteId($website->getWebsiteId());
        $group->setName($storeName);
        $group->setCode($storeCode);
        $this->groupResourceModel->save($group);
        return $group;
    }
    return null;
}

When I create the store for the first time with the store code my_store it works fine; I can see that it is logged in store_group table.

The second time I run it I am expecting it to give me the store thanks to $this->storeRepository->get($storeCode) but it doesn’t find the store… I know this because if I remove the try/catch it will return an exception:

The store that was requested wasn't found. Verify the store and try again.

So how would I check if the store already exists by code?

Can someone please explain the difference between store and group?

One Answer

How would I check if the store already exists by code?

Your approach is correct.

Example Code :

try {
    $this->storeRepository->get($storeCode);
} catch (NoSuchEntityException $nsee) {
    // Requested store doesn't exist
}

Difference between store and group

If you will see grid under Stores -> All Stores, you will see three columns Web Site, Store and Store View
Web Site is mapped to the store_website table in the database.
Store is mapped to the store_group table in the database.
Store View is mapped to the store table in the database.

So, the $group is nothing but the store_group which is the representation of the store entity only.

Answered by Anshu Mishra on December 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP