如何在独立项目中复用Sylius组件?数据库表映射遇阻求助
Hey there! I’ve run into exactly this issue when trying to reuse Sylius components in a standalone project—let’s walk through how to get those database tables created properly.
Step 1: Locate Sylius Component’s Doctrine Mapping Files
Sylius components come with pre-built Doctrine ORM mappings (usually in XML format) for their core models. For the Order component, you’ll find these files in:vendor/sylius/order/Resources/config/doctrine
Inside, you’ll see mappings for Order, OrderItem, and other related models that define their database structure.
Step 2: Configure Doctrine to Load These Mappings
You need to tell Doctrine where to find these mapping files so it can recognize Sylius’s models. The setup varies a bit depending on your project type:
For Standalone Doctrine Projects
Update your main Doctrine configuration file (typically cli-config.php) to include the Sylius mapping path:
use Doctrine\ORM\Tools\Setup; use Doctrine\ORM\EntityManager; // Define paths to your project's entities AND Sylius's mapping files $mappingPaths = [ __DIR__ . '/src/Entity', // Your project's custom entities __DIR__ . '/vendor/sylius/order/Resources/config/doctrine', // Sylius Order mappings ]; $isDevMode = true; $dbConnectionParams = [ 'driver' => 'pdo_mysql', 'user' => 'your_db_user', 'password' => 'your_db_password', 'dbname' => 'your_db_name', ]; // Use XML configuration since Sylius uses XML mappings $config = Setup::createXMLMetadataConfiguration($mappingPaths, $isDevMode); $entityManager = EntityManager::create($dbConnectionParams, $config);
For Symfony Projects
Add the Sylius mapping to your config/packages/doctrine.yaml:
doctrine: orm: mappings: SyliusOrder: is_bundle: false type: xml dir: '%kernel.project_dir%/vendor/sylius/order/Resources/config/doctrine' prefix: 'Sylius\Component\Order\Model' alias: SyliusOrder
Step 3: Generate the Database Schema
Once the mappings are configured, run Doctrine’s schema tool command to create or update your database tables:
# For standalone projects ./vendor/bin/doctrine orm:schema-tool:create # For Symfony projects bin/console doctrine:schema:update --force
Common Troubleshooting Tips
- Incorrect Mapping Path: Double-check the path to Sylius’s doctrine config directory—some older versions might have slightly different structures. Navigate to
vendor/sylius/orderto confirm the exact path. - Mismatched Mapping Type: If Sylius uses XML mappings (most do), don’t use Doctrine’s annotation configuration. Stick to
createXMLMetadataConfigurationor specifytype: xmlin Symfony’s config. - Missing Dependencies: Ensure all required Sylius components are installed (e.g.,
sylius/resource,sylius/money—these are dependencies of the Order component and their mappings might be required too).
内容的提问来源于stack exchange,提问作者Peter Clayder

