Search code examples
dbalshopware

Load Categorywith id in bootstrap.php Shopware 5


in my bootstrap.php I try to load a category with a special id. Its not quite working.

    public function getCatFromDb($idCat){
    /** @var \Doctrine\DBAL\Connection $connection */
    $connection = $connection->get('dbal_connection');
    $sql = 'SELECT * FROM s_categories WHERE id=$idCat';
    $result = $connection->query($sql)->fetch();
    var_dump($result);

    return $result;
}

Can someone spot the mistake? Thanks in advance!


Solution

  • You should use the ModelManager to retrieve the Category.

    /** @var ModelManager $modelManager */
    $modelManager = Shopware()->Container()->get('models');
    // you could use this, too
    // $modelManager = $this->container->get('models');
    /** @var Category $category */
    $category = $modelManager->getRepository(Category::class)->find($id);