话说这篇文章真是在没有任何实例的情况下帮了大忙
另外附上我自己的一个完整demo:https://github.com/LearnForInterest/material
结合了ci框架的doctrine使用
原文地址:http://www.xuejiehome.com/blread-1920.html#index_6
一、配置数据库
二、创建和生成数据库表结构
三、从已有数据库生成Entity
四、保存数据到数据库
五、从数据库读取
六、更新记录
七、删除记录
八、工作笔记记录(可跳过):
Symfony和Doctrine进行了集成,Doctrine类库全部目标就是给你一个强大的工具,让你的工作更加容易。
Doctrine是完全解耦与Symfony的,所以并不一定要使用它。
一个简单例子:一个产品,我们首先来配置数据库,创建一个Product对象,添加到数据库并把它读回来。
首先,我们需要创建一个bundle:
1 |
$php app/console generate:bundle --namespace=Blog/StoreBundle |
一、配置数据库
在开始之前,首先需要配置数据库连接信息。根据惯例,这些信息通常会配置在app/config/parameters.yml 文件中。
04 |
mailer_transport: smtp |
05 |
mailer_host: 127.0.0.1 |
09 |
secret: 256d7de0d269e37752b49fec38f5fc5e |
11 |
debug_redirects: false |
12 |
use_assetic_controller: true |
15 |
database_driver: pdo_mysql |
16 |
database_host: 127.0.0.1 |
18 |
database_name: symfony |
20 |
database_password: 123 |
将配置信息定义到parameters.yml文件中也是一个常用的做法。定义在该文件中的配置信息将会被主配置文件在安装Doctrine时引用。
06 |
default_connection: default |
09 |
driver: "%database_driver%" |
10 |
host: "%database_host%" |
11 |
port: "%database_port%" |
12 |
user: "%database_user%" |
13 |
password: "%database_password%" |
15 |
dbname: "%database_name%" |
22 |
auto_generate_proxy_classes: "%kernel.debug%" |
以上文件中dbal和orm中的default均可以复制后更改以实现多个数据库链接。
在config.yml中导入上面的两个yml配置文件:
4 |
- { resource: parameters.yml } |
5 |
- { resource: doctrine.yml } |
6 |
- { resource: security.yml } |
通过把数据库信息分离到一个特定的文件中,你可以很容易的为每个服务器保存不同的版本。现在Doctrine知道你的数据库配置了,你可以用它来创建一个数据库了。
二、创建和生成数据库表结构
(1)创建数据库
1 |
$php app/console doctrine:database:create —em=“default” |
执行上面命令的时候可能会出现“[DoctrineDBALExceptionConnectionException]An exception occured in driver: SQLSTATE[HY000] [2002] No such file or directory ”的错误,将database_host由localhost改为127.0.0.1即可。
(2)通过entity生成数据库表结构
创建基础的Entity实体类:
假设你创建一个应用程序,其中有些产品需要展示。即时不考虑Doctrine或者数据库,你也应该知道你需要一个Product对象来表现这些产品。在你的StoreBundle的Entity目录下创建一个实体类(Entity)。
03 |
namespace Blog\StoreBundle\Entity; |
09 |
protected $description; |
这样的类经常被称为“Entity”,把表中的字段映射到该类。不过现在它还不能被保存到数据库中,因为现在它只不过还是个简单的PHP类。一旦你学习了Doctrine背后的概念,你可以让Doctrine来为你创建实体类。
创建完整的Entity实体类:
1 |
php app/console doctrine:generate:entity --entity="StoreBundle:Product" --fields="name:string(255) price:float description:text" --with-repository |
005 |
namespace Blog\StoreBundle\Entity; |
007 |
use DoctrineORMMapping as ORM; |
045 |
private $description; |
053 |
public function getId() |
064 |
public function setName($name) |
076 |
public function getName() |
087 |
public function setPrice($price) |
089 |
$this->price = $price; |
099 |
public function getPrice() |
110 |
public function setDescription($description) |
112 |
$this->description = $description; |
122 |
public function getDescription() |
124 |
return $this->description; |
根据Entity生成数据库:
1 |
php app/console doctrine:schema:update --force --em="default" |
看到如下提示即为成功:
Updating database schema...
Database schema updated successfully! "1" queries were executed
三、从已有数据库生成Entity
2 |
php app/console doctrine:mapping:import --force StoreBundle annotation |
4 |
app/console doctrine:mapping:import --em="default" StoreBundle --filter=Product annotation |
6 |
php app/console doctrine:generate:entities BlogStoreBundle |
注意:
(1)--em="default"中的default是指connection,对应第一步配置数据库信息(doctrine.yml)中的default
(2)--filter=Product 这里的P是大写的,它的规则跟生成的类名是一致的(采用驼峰型)
例如:
1 |
表名: article --filter=Article |
2 |
表名:test_article --filter=TestArticle |
3 |
表名:test_article_detail --filter=TestArticleDetail |
四、保存数据到数据库
04 |
use Blog\StoreBundle\Entity\Product; |
06 |
use Symfony\Component\HttpFoundation\Response; |
07 |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; |
10 |
public function createAction() |
12 |
$product = new Product(); |
13 |
$product->setName('A Foo Bar'); |
14 |
$product->setPrice('19.99'); |
15 |
$product->setDescription('Lorem ipsum dolor'); |
17 |
$em = $this->getDoctrine()->getManager(); |
19 |
$em->persist($product); |
22 |
return new Response('Created product id '.$product->getId()); |
配置路由:
5 |
defaults: { _controller: TestBundle:Default:create } |
五、从数据库读取
01 |
public function showAction($id) |
03 |
$product = $this->getDoctrine() |
04 |
->getRepository('AcmeStoreBundle:Product') |
07 |
throw $this->createNotFoundException('No product found for id ' .$id); |
配置路由:
5 |
defaults: { _controller: TestBundle:Default:show } |
其他查询方式可参考:Symfony2 Doctrine 数据库查询方法总结
六、更新记录
01 |
public function updateAction($id) |
03 |
$em = $this->getDoctrine()->getEntityManager(); |
04 |
$product = $em->getRepository('AcmeStoreBundle:Product')->find($id); |
07 |
throw $this->createNotFoundException('No product found for id '.$id); |
10 |
$product->setName('New product name!'); |
13 |
return $this->redirect($this->generateUrl('homepage')); |
更新记录仅需要三步:
1. 从Doctrine找到对象
2. 修改这个对象
3. 调用entity manager的flush函数
注意:
$em->persist($product)没有必要,这个方法仅仅是要告诉Doctrine去管理或者观看$product对象,当你从Doctrine中找到了$product对象,它已经被管理了。
Notice that calling $em->persist($product) isn't necessary. Recall that this method simply tells
Doctrine to manage or "watch" the $product object. In this case, since you fetched the $product object
from Doctrine, it's already managed.
七、删除记录
八、工作笔记记录(可跳过):
1. 增加记录:
1.1 单表增加
01 |
use Acme\StoreBundle\Entity\Product; |
03 |
public function createAction() |
05 |
$product = new Product(); |
06 |
$product->setName('A Foo Bar'); |
07 |
$product->setPrice('19.99'); |
08 |
$product->setDescription('Lorem ipsum dolor'); |
09 |
$em = $this->getDoctrine()->getManager(); |
10 |
$em->persist($product); |
12 |
return new Response('Created product id '.$product->getId()); |
1.2 多表增加
01 |
use Acme\StoreBundle\Entity\Category; |
02 |
use Acme\StoreBundle\Entity\Product; |
04 |
use Symfony\Component\HttpFoundation\Response; |
05 |
class DefaultController extends Controller |
07 |
public function createProductAction() |
09 |
$category = new Category(); |
10 |
$category->setName('Main Products'); |
11 |
$product = new Product(); |
12 |
$product->setName('Foo'); |
13 |
$product->setPrice(19.99); |
15 |
$product->setCategory($category); |
16 |
$em = $this->getDoctrine()->getManager(); |
17 |
$em->persist($category); |
18 |
$em->persist($product); |
21 |
'Created product id: '.$product->getId() |
22 |
.' and category id: '.$category->getId() |
1.3 批量插入函数
08 |
function ucWords($str) |
10 |
$str = ucwords(str_replace('_', ' ', $str)); |
11 |
$str = str_replace(' ', '', $str); |
23 |
function batchInsertByEntity($entity, $dataList, $per = 1000) |
25 |
$count = count($dataList); |
26 |
for ($i = 0; $i < $count; $i ++) { |
28 |
foreach ($dataList[$i] as $k => $v) { |
29 |
$obj->{"set" . $this->ucWords($k)}($v); |
31 |
$this->em->persist($obj); |
32 |
if (($count % $per) === 0) { |
(2)删除记录:
01 |
public function deleteAction($id) |
03 |
$em = $this->getDoctrine()->getManager(); |
04 |
$product = $em->getRepository('AcmeStoreBundle:Product')->find($id); |
07 |
throw $this->createNotFoundException( |
08 |
'No product found for id '.$id |
12 |
$em->remove($product); |
14 |
return $this->redirect($this->generateUrl('homepage')); |
(3)查询记录:
参看这篇文章:Symfony2 Doctrine 数据库查询方法总结
一、配置数据库
二、创建和生成数据库表结构
三、从已有数据库生成Entity
四、保存数据到数据库
五、从数据库读取
六、更新记录
七、删除记录
八、工作笔记记录(可跳过):
Symfony和Doctrine进行了集成,Doctrine类库全部目标就是给你一个强大的工具,让你的工作更加容易。
Doctrine是完全解耦与Symfony的,所以并不一定要使用它。
一个简单例子:一个产品,我们首先来配置数据库,创建一个Product对象,添加到数据库并把它读回来。
首先,我们需要创建一个bundle:
1 |
$php app/console generate:bundle --namespace=Blog/StoreBundle |
一、配置数据库
在开始之前,首先需要配置数据库连接信息。根据惯例,这些信息通常会配置在app/config/parameters.yml 文件中。
04 |
mailer_transport: smtp |
05 |
mailer_host: 127.0.0.1 |
09 |
secret: 256d7de0d269e37752b49fec38f5fc5e |
11 |
debug_redirects: false |
12 |
use_assetic_controller: true |
15 |
database_driver: pdo_mysql |
16 |
database_host: 127.0.0.1 |
18 |
database_name: symfony |
20 |
database_password: 123 |
将配置信息定义到parameters.yml文件中也是一个常用的做法。定义在该文件中的配置信息将会被主配置文件在安装Doctrine时引用。
06 |
default_connection: default |
09 |
driver: "%database_driver%" |
10 |
host: "%database_host%" |
11 |
port: "%database_port%" |
12 |
user: "%database_user%" |
13 |
password: "%database_password%" |
15 |
dbname: "%database_name%" |
22 |
auto_generate_proxy_classes: "%kernel.debug%" |
以上文件中dbal和orm中的default均可以复制后更改以实现多个数据库链接。
在config.yml中导入上面的两个yml配置文件:
4 |
- { resource: parameters.yml } |
5 |
- { resource: doctrine.yml } |
6 |
- { resource: security.yml } |
通过把数据库信息分离到一个特定的文件中,你可以很容易的为每个服务器保存不同的版本。现在Doctrine知道你的数据库配置了,你可以用它来创建一个数据库了。
二、创建和生成数据库表结构
(1)创建数据库
1 |
$php app/console doctrine:database:create —em=“default” |
执行上面命令的时候可能会出现“[DoctrineDBALExceptionConnectionException]An exception occured in driver: SQLSTATE[HY000] [2002] No such file or directory ”的错误,将database_host由localhost改为127.0.0.1即可。
(2)通过entity生成数据库表结构
创建基础的Entity实体类:
假设你创建一个应用程序,其中有些产品需要展示。即时不考虑Doctrine或者数据库,你也应该知道你需要一个Product对象来表现这些产品。在你的StoreBundle的Entity目录下创建一个实体类(Entity)。
03 |
namespace Blog\StoreBundle\Entity; |
09 |
protected $description; |
这样的类经常被称为“Entity”,把表中的字段映射到该类。不过现在它还不能被保存到数据库中,因为现在它只不过还是个简单的PHP类。一旦你学习了Doctrine背后的概念,你可以让Doctrine来为你创建实体类。
创建完整的Entity实体类:
1 |
php app/console doctrine:generate:entity --entity="StoreBundle:Product" --fields="name:string(255) price:float description:text" --with-repository |
005 |
namespace Blog\StoreBundle\Entity; |
007 |
use DoctrineORMMapping as ORM; |
045 |
private $description; |
053 |
public function getId() |
064 |
public function setName($name) |
076 |
public function getName() |
087 |
public function setPrice($price) |
089 |
$this->price = $price; |
099 |
public function getPrice() |
110 |
public function setDescription($description) |
112 |
$this->description = $description; |
122 |
public function getDescription() |
124 |
return $this->description; |
根据Entity生成数据库:
1 |
php app/console doctrine:schema:update --force --em="default" |
看到如下提示即为成功:
Updating database schema...
Database schema updated successfully! "1" queries were executed
三、从已有数据库生成Entity
2 |
php app/console doctrine:mapping:import --force StoreBundle annotation |
4 |
app/console doctrine:mapping:import --em="default" StoreBundle --filter=Product annotation |
6 |
php app/console doctrine:generate:entities BlogStoreBundle |
注意:
(1)--em="default"中的default是指connection,对应第一步配置数据库信息(doctrine.yml)中的default
(2)--filter=Product 这里的P是大写的,它的规则跟生成的类名是一致的(采用驼峰型)
例如:
1 |
表名: article --filter=Article |
2 |
表名:test_article --filter=TestArticle |
3 |
表名:test_article_detail --filter=TestArticleDetail |
四、保存数据到数据库
04 |
use Blog\StoreBundle\Entity\Product; |
06 |
use Symfony\Component\HttpFoundation\Response; |
07 |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; |
10 |
public function createAction() |
12 |
$product = new Product(); |
13 |
$product->setName('A Foo Bar'); |
14 |
$product->setPrice('19.99'); |
15 |
$product->setDescription('Lorem ipsum dolor'); |
17 |
$em = $this->getDoctrine()->getManager(); |
19 |
$em->persist($product); |
22 |
return new Response('Created product id '.$product->getId()); |
配置路由:
5 |
defaults: { _controller: TestBundle:Default:create } |
五、从数据库读取
01 |
public function showAction($id) |
03 |
$product = $this->getDoctrine() |
04 |
->getRepository('AcmeStoreBundle:Product') |
07 |
throw $this->createNotFoundException('No product found for id ' .$id); |
配置路由:
5 |
defaults: { _controller: TestBundle:Default:show } |
其他查询方式可参考:Symfony2 Doctrine 数据库查询方法总结
六、更新记录
01 |
public function updateAction($id) |
03 |
$em = $this->getDoctrine()->getEntityManager(); |
04 |
$product = $em->getRepository('AcmeStoreBundle:Product')->find($id); |
07 |
throw $this->createNotFoundException('No product found for id '.$id); |
10 |
$product->setName('New product name!'); |
13 |
return $this->redirect($this->generateUrl('homepage')); |
更新记录仅需要三步:
1. 从Doctrine找到对象
2. 修改这个对象
3. 调用entity manager的flush函数
注意:
$em->persist($product)没有必要,这个方法仅仅是要告诉Doctrine去管理或者观看$product对象,当你从Doctrine中找到了$product对象,它已经被管理了。
Notice that calling $em->persist($product) isn't necessary. Recall that this method simply tells
Doctrine to manage or "watch" the $product object. In this case, since you fetched the $product object
from Doctrine, it's already managed.
七、删除记录
八、工作笔记记录(可跳过):
1. 增加记录:
1.1 单表增加
01 |
use Acme\StoreBundle\Entity\Product; |
03 |
public function createAction() |
05 |
$product = new Product(); |
06 |
$product->setName('A Foo Bar'); |
07 |
$product->setPrice('19.99'); |
08 |
$product->setDescription('Lorem ipsum dolor'); |
09 |
$em = $this->getDoctrine()->getManager(); |
10 |
$em->persist($product); |
12 |
return new Response('Created product id '.$product->getId()); |
1.2 多表增加
01 |
use Acme\StoreBundle\Entity\Category; |
02 |
use Acme\StoreBundle\Entity\Product; |
04 |
use Symfony\Component\HttpFoundation\Response; |
05 |
class DefaultController extends Controller |
07 |
public function createProductAction() |
09 |
$category = new Category(); |
10 |
$category->setName('Main Products'); |
11 |
$product = new Product(); |
12 |
$product->setName('Foo'); |
13 |
$product->setPrice(19.99); |
15 |
$product->setCategory($category); |
16 |
$em = $this->getDoctrine()->getManager(); |
17 |
$em->persist($category); |
18 |
$em->persist($product); |
21 |
'Created product id: '.$product->getId() |
22 |
.' and category id: '.$category->getId() |
1.3 批量插入函数
08 |
function ucWords($str) |
10 |
$str = ucwords(str_replace('_', ' ', $str)); |
11 |
$str = str_replace(' ', '', $str); |
23 |
function batchInsertByEntity($entity, $dataList, $per = 1000) |
25 |
$count = count($dataList); |
26 |
for ($i = 0; $i < $count; $i ++) { |
28 |
foreach ($dataList[$i] as $k => $v) { |
29 |
$obj->{"set" . $this->ucWords($k)}($v); |
31 |
$this->em->persist($obj); |
32 |
if (($count % $per) === 0) { |
(2)删除记录:
01 |
public function deleteAction($id) |
03 |
$em = $this->getDoctrine()->getManager(); |
04 |
$product = $em->getRepository('AcmeStoreBundle:Product')->find($id); |
07 |
throw $this->createNotFoundException( |
08 |
'No product found for id '.$id |
12 |
$em->remove($product); |
14 |
return $this->redirect($this->generateUrl('homepage')); |
(3)查询记录:
参看这篇文章:Symfony2 Doctrine 数据库查询方法总结