首页 > 技术文章 > symfony doctrine generate entity repository

codesay 2013-08-13 19:15 原文

symfony+doctrine是我们正在用的一套框架,用于设计后台。其强大的命令行可以帮助我们生成一部分代码。
本文讲一下,建完数据库之后,如何使用命令行生成相应的entity&repository.

CREATE TABLE `download_ranking_coefficient` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category_level1_id` int(11) unsigned NOT NULL default 0 COMMENT '分类',
  `pre30d_users` ENUM('70', '80', '90') NOT NULL default '80',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY cate_create (`category_level1_id`, `create_time`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

 

Q1:本表中使用了ENUM数据类型, doctrine默认无法生成entity文件。

A1:需要在config.yml doctrine增加如下配置项

doctrine:
    dbal:
        default_connection:   default
        connections:
            default:
                driver:   %database_driver%
                host:     %database_host%
                port:     %database_port%
                dbname:   %database_name%
                user:     %database_user%
                password: %database_password%
                charset:  UTF8
            show:
                driver:   %database_driver_show%
                host:     %database_host_show%
                port:     %database_port_show%
                dbname:   %database_name_show%
                user:     %database_user_show%
                password: %database_password_show%
                charset:  UTF8
                mapping_types: 
                            enum:       string 
                #   在show配置项增加 mapping_types 配置自己所需类型映射。

 

执行命令

php app/console doctrine:mapping:import "YourAppBundle" annotation --em=show --filter=DownloadRankingCoefficient
php app/console doctrine:generate:entities --no-backup YourAppBundle:DownloadRankingCoefficient


执行完命令可以生成带成员变量&set&get函数的Entity, 但是如何生成Repository? 

/**
 * DownloadRankingCoefficient
 *
 * @ORM\Table(name="download_ranking_coefficient")
 * @ORM\Entity
 */
修改为
/**
 * DownloadRankingCoefficient
 *
 * @ORM\Table(name="download_ranking_coefficient")
 * @ORM\Entity(repositoryClass="Your\AppBundle\Repository\DownloadRankingDataRepository")
 */


再次执行2次如下命令(--no-backup不会生成~结尾的文件)

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


大功告成!

有些时候使用orm插入数据需要大量的set函数,看着非常不美观。自己有一段代码觉得很好用,分享一下。

# $data中是多行数据库数据
$em = $this->getDoctrine()->getManager("yourDb");
foreach($data as $rankingItem) {
    $rankingObj = new DownloadRankingData();
    foreach($rankingItem as $key=>$value) {
        $value = $value === null ? 0 : $value;
        $function = 'set'.str_replace(' ','',ucwords(str_replace('_', ' ', $key)));
        $rankingObj->$function($value);
    }
    $em->persist($rankingObj);
    $em->flush();
}

 

参考文献:

1. http://symfony.com/doc/current/book/doctrine.html

2. http://blog.alterphp.com/2011/09/deal-with-mysql-types-natively.html

3. http://stackoverflow.com/questions/8312271/how-to-enable-enums-in-symfony-2-doctrine

推荐阅读