如何在Symfony2中从现有表生成实体?

10

我有一张名为"my_table"的表格,其中包含几个字段。 我想在MyBundle中生成一个实体来使用"my_table"表格。但是我不想重新创建所有实体。 我该如何做到这一点?


3
http://symfony.com/doc/2.0/cookbook/doctrine/reverse_engineering.html - Molecular Man
4个回答

16

以下是您可以完成它的方式,

第一步,请让Doctrine自我检查数据库并生成相应的xml或yml元数据文件。

php app/console doctrine:mapping:convert [xml|yml] Path/To/MyBundle/Resources/config/doctrine/metadata/orm --from-database --force --filter=MyTable

第二步,执行以下两个命令,要求Doctrine导入模式并构建相关的实体类。

php app/console doctrine:mapping:import MyBundle [xml|yml|annotation] --filter=MyTable

php app/console doctrine:generate:entities Path\To\MyBundle\EntityFolder\\MyTable

请查看文档中的如何从现有数据库生成实体部分


1
在最终的命令中,我能够使用快捷方式MyBundle:MyTable代替Path\To\MyBundle\EntityFolder\\MyTable - Nate

6

针对Symfony 2.7选项注释的简单工作解决方案,对于[/xml/yml],请参阅http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html

在3步中执行3个命令:

命令#1:

$ php app/console doctrine:mapping:import --force AppBundle xml --filter="Meeting"

输出:

正在写入 C:\xampp\htdocs\localxyz\src\AppBundle/Resources/config/doctrine/Meeting.orm.xml


命令 #2:

$ php app/console doctrine:mapping:convert annotation ./src/AppBundle/Entity --from-database --filter="Meeting"

输出:

正在处理实体“Meeting”

将“注释”映射信息导出到“C:\xampp\htdocs\localxyz\src\Entity”


命令#3:

$ php app/console doctrine:generate:entities AppBundle:Meeting --no-backup

输出:

正在生成实体 "AppBundle\Entity\Meeting" 正在生成 AppBundle\Entity\Meeting

其中:

AppBundle 是您在Symfony 2.7中的“AppBundle” Meeting 是目标表格(区分大小写)

要确定,请检查此目录:

C:\xampp\htdocs\myproj\src\AppBundle/Resources/config/doctrine/Meeting.orm.xml

C:\xampp\htdocs\myproj\src\AppBundle/Resources/config/doctrine/MeetingOriginal.orm.xml

并确保您仅拥有 .xml 文件来创建实体类文件,而没有其他文件。

这对我非常有效。

如需说明,请阅读:http://symfony.com/doc/current/cookbook/doctrine/reverse_engineering.html


如果您使用默认实体管理器,则此方法可以正常工作。如果您需要从不同的数据库中提取数据,请提供以下参数: --em="实体管理器名称" - Jignesh Rawal

2

虽然这是一篇旧文章,但如果有人遇到以下错误:

Database does not have any mapping information.

请检查

如果您的表名为blog_post,则在筛选选项中使用BlogPost而不是blog_post

参考:https://dev59.com/e3_aa4cB1Zd3GeqPziu3#27019561

尽管这已经被上面的答案所涵盖,但我错过了它并且一直收到这个错误

所以我想明确说明一下

在Symfony >= 3.4中,也要使用php bin/console,例如:

php bin/console doctrine:mapping:import --force AppBundle xml --filter="BlogPost"

然后

php bin/console doctrine:mapping:convert annotation ./src/AppBundle/Entity --from-database --filter="BlogPost"

感谢您的提问。


2
php app/console doctrine:mapping:import "MyCustomBundle" xml --filter=MyMatchedEntity

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接