话说这篇文章真是在没有任何实例的情况下帮了大忙
另外附上我自己的一个完整demo:https://github.com/LearnForInterest/material
结合了ci框架的doctrine使用
原文地址:http://www.xuejiehome.com/blread-1920.html#index_6
Symfony和Doctrine进行了集成,Doctrine类库全部目标就是给你一个强大的工具,让你的工作更加容易。
Doctrine是完全解耦与Symfony的,所以并不一定要使用它。
一个简单例子:一个产品,我们首先来配置数据库,创建一个Product对象,添加到数据库并把它读回来。
首先,我们需要创建一个bundle:
1 |
$php app/console generate:bundle --namespace=Blog/StoreBundle |
一、配置数据库
在开始之前,首先需要配置数据库连接信息。根据惯例,这些信息通常会配置在app/config/parameters.yml 文件中。
01 |
#app/config/parameters.yml |
02 |
# This file is auto-generated during the composer install |
03 |
parameters: |
04 |
mailer_transport: smtp |
05 |
mailer_host: 127.0.0.1 |
06 |
mailer_user: null |
07 |
mailer_password: null |
08 |
locale: zh_CN |
09 |
secret: 256d7de0d269e37752b49fec38f5fc5e |
10 |
debug_toolbar: true |
11 |
debug_redirects: false |
12 |
use_assetic_controller: true |
13 |
database_path: null |
14 |
assets_version: 0 |
15 |
database_driver: pdo_mysql |
16 |
database_host: 127.0.0.1 |
17 |
database_port: 3306 |
18 |
database_name: symfony |
19 |
database_user: root |
20 |
database_password: 123 |
将配置信息定义到parameters.yml文件中也是一个常用的做法。定义在该文件中的配置信息将会被主配置文件在安装Doctrine时引用。
01 |
#app/config/doctrine.yml |
02 |
|
03 |
# Doctrine Configuration |
04 |
doctrine: |
05 |
dbal: |
06 |
default_connection: default |
07 |
connections: |
08 |
default: |
09 |
driver: "%database_driver%" |
10 |
host: "%database_host%" |
11 |
port: "%database_port%" |
12 |
user: "%database_user%" |
13 |
password: "%database_password%" |
14 |
charset: UTF8 |
15 |
dbname: "%database_name%" |
16 |
|
17 |
# if using pdo_sqlite as your database driver, add the path in parameters.yml |
18 |
# e.g. database_path: "%kernel.root_dir%/data/data.db3" |
19 |
# path: "%database_path%" |
20 |
|
21 |
orm: |
22 |
auto_generate_proxy_classes: "%kernel.debug%" |
23 |
#auto_mapping: true |
24 |
entity_managers: |
25 |
default: |
26 |
connection: default |
27 |
mappings: |
28 |
StoreBundle: ~ |
以上文件中dbal和orm中的default均可以复制后更改以实现多个数据库链接。
在config.yml中导入上面的两个yml配置文件:
1 |
#app/config/config.yml |
2 |
|
3 |
imports: |
4 |
- { resource: parameters.yml } |
5 |
- { resource: doctrine.yml } |
6 |
- { resource: security.yml } |
通过把数据库信息分离到一个特定的文件中,你可以很容易的为每个服务器保存不同的版本。现在Doctrine知道你的数据库配置了,你可以用它来创建一个数据库了。
二、创建和生成数据库表结构
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)。
01 |
// src/Blog/StoreBundle/Entity/Product.php |
02 |
|
03 |
namespace Blog\StoreBundle\Entity; |
04 |
|
05 |
class Product |
06 |
{ |
07 |
protected $name ; |
08 |
protected $price ; |
09 |
protected $description ; |
10 |
} |
这样的类经常被称为“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 |
001 |
// src/Blog/StoreBundle/Entity/Product.php |
002 |
|
003 |
<?php |
004 |
|
005 |
namespace Blog\StoreBundle\Entity; |
006 |
|
007 |
use DoctrineORMMapping as ORM; |
008 |
|
009 |
/** |
010 |
* Product |
011 |
* |
012 |
* @ORMTable() |
013 |
* @ORMEntity(repositoryClass="BlogStoreBundleEntityProductRepository") |
014 |
*/ |
015 |
class Product |
016 |
{ |
017 |
/** |
018 |
* @var integer |
019 |
* |
020 |
* @ORMColumn(name="id", type="integer") |
021 |
* @ORMId |
022 |
* @ORMGeneratedValue(strategy="AUTO") |
023 |
*/ |
024 |
private $id ; |
025 |
|
026 |
/** |
027 |
* @var string |
028 |
* |
029 |
* @ORMColumn(name="name", type="string", length=255) |
030 |
*/ |
031 |
private $name ; |
032 |
|
033 |
/** |
034 |
* @var float |
035 |
* |
036 |
* @ORMColumn(name="price", type="float") |
037 |
*/ |
038 |
private $price ; |
039 |
|
040 |
/** |
041 |
* @var string |
042 |
* |
043 |
* @ORMColumn(name="description", type="text") |
044 |
*/ |
045 |
private $description ; |
046 |
|
047 |
|
048 |
/** |
049 |
* Get id |
050 |
* |
051 |
* @return integer |
052 |
*/ |
053 |
public function getId() |
054 |
{ |
055 |
return $this ->id; |
056 |
} |
057 |
|
058 |
/** |
059 |
* Set name |
060 |
* |
061 |
* @param string $name |
062 |
* @return Product |
063 |
*/ |
064 |
public function setName( $name ) |
065 |
{ |
066 |
$this ->name = $name ; |
067 |
|
068 |
return $this ; |
069 |
} |
070 |
|
071 |
/** |
072 |
* Get name |
073 |
* |
074 |
* @return string |
075 |
*/ |
076 |
public function getName() |
077 |
{ |
078 |
return $this ->name; |
079 |
} |
080 |
|
081 |
/** |
082 |
* Set price |
083 |
* |
084 |
* @param float $price |
085 |
* @return Product |
086 |
*/ |
087 |
public function setPrice( $price ) |
088 |
{ |
089 |
$this ->price = $price ; |
090 |
|
091 |
return $this ; |
092 |
} |
093 |
|
094 |
/** |
095 |
* Get price |
096 |
* |
097 |
* @return float |
098 |
*/ |
099 |
public function getPrice() |
100 |
{ |
101 |
return $this ->price; |
102 |
} |
103 |
|
104 |
/** |
105 |
* Set description |
106 |
* |
107 |
* @param string $description |
108 |
* @return Product |
109 |
*/ |
110 |
public function setDescription( $description ) |
111 |
{ |
112 |
$this ->description = $description ; |
113 |
|
114 |
return $this ; |
115 |
} |
116 |
|
117 |
/** |
118 |
* Get description |
119 |
* |
120 |
* @return string |
121 |
*/ |
122 |
public function getDescription() |
123 |
{ |
124 |
return $this ->description; |
125 |
} |
126 |
} |
根据Entity生成数据库:
1 |
php app/console doctrine:schema:update --force --em= "default" |
看到如下提示即为成功:
Updating database schema...
Database schema updated successfully! "1" queries were executed
三、从已有数据库生成Entity
1 |
#生成Entity基础字段: |
2 |
php app/console doctrine:mapping: import --force StoreBundle annotation |
3 |
#根据数据库结构生成Product表的Entity |
4 |
app/console doctrine:mapping: import --em= "default" StoreBundle --filter=Product annotation |
5 |
#生成get/set方法: |
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 |
四、保存数据到数据库
01 |
// src/Blog/TestBundle/Controller/DefaultController.php |
02 |
|
03 |
// ... |
04 |
use Blog\StoreBundle\Entity\Product; |
05 |
|
06 |
use Symfony\Component\HttpFoundation\Response; |
07 |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; |
08 |
|
09 |
// ... |
10 |
public function createAction() |
11 |
{ |
12 |
$product = new Product(); |
13 |
$product ->setName( 'A Foo Bar' ); |
14 |
$product ->setPrice( '19.99' ); |
15 |
$product ->setDescription( 'Lorem ipsum dolor' ); |
16 |
|
17 |
$em = $this ->getDoctrine()->getManager(); |
18 |
|
19 |
$em ->persist( $product ); |
20 |
$em -> flush (); |
21 |
|
22 |
return new Response( 'Created product id ' . $product ->getId()); |
23 |
} |
配置路由:
1 |
#src/Blog/TestBundle/Resources/config/routing.yml |
2 |
|
3 |
test_create: |
4 |
path: / test /create |
5 |
defaults: { _controller: TestBundle:Default:create } |
五、从数据库读取
01 |
public function showAction( $id ) |
02 |
{ |
03 |
$product = $this ->getDoctrine() |
04 |
->getRepository( 'AcmeStoreBundle:Product' ) |
05 |
->find( $id ); |
06 |
if (! $product ){ |
07 |
throw $this ->createNotFoundException( 'No product found for id ' . $id ); |
08 |
} |
09 |
//do something,想把$product对象传递给一个template等。 |
10 |
} |
配置路由:
1 |
#src/Blog/TestBundle/Resources/config/routing.yml |
2 |
|
3 |
test_show: |
4 |
path: /show/{ id } |
5 |
defaults: { _controller: TestBundle:Default:show } |
其他查询方式可参考:Symfony2 Doctrine 数据库查询方法总结
六、更新记录
01 |
public function updateAction( $id ) |
02 |
{ |
03 |
$em = $this ->getDoctrine()->getEntityManager(); |
04 |
$product = $em ->getRepository( 'AcmeStoreBundle:Product' )->find( $id ); |
05 |
|
06 |
if (! $product ) { |
07 |
throw $this ->createNotFoundException( 'No product found for id ' . $id ); |
08 |
} |
09 |
|
10 |
$product ->setName( 'New product name!' ); |
11 |
$em -> flush (); |
12 |
|
13 |
return $this ->redirect( $this ->generateUrl( 'homepage' )); |
14 |
} |
更新记录仅需要三步:
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 |
$em ->remove( $product ); |
2 |
$em -> flush (); |
八、工作笔记记录(可跳过):
1.1 单表增加
01 |
use Acme\StoreBundle\Entity\Product; |
02 |
|
03 |
public function createAction() |
04 |
{ |
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 ); |
11 |
$em -> flush (); |
12 |
return new Response( 'Created product id ' . $product ->getId()); |
13 |
} |
1.2 多表增加
01 |
use Acme\StoreBundle\Entity\Category; |
02 |
use Acme\StoreBundle\Entity\Product; |
03 |
|
04 |
use Symfony\Component\HttpFoundation\Response; |
05 |
class DefaultController extends Controller |
06 |
{ |
07 |
public function createProductAction() |
08 |
{ |
09 |
$category = new Category(); |
10 |
$category ->setName( 'Main Products' ); |
11 |
$product = new Product(); |
12 |
$product ->setName( 'Foo' ); |
13 |
$product ->setPrice(19.99); |
14 |
// relate this product to the category |
15 |
$product ->setCategory( $category ); |
16 |
$em = $this ->getDoctrine()->getManager(); |
17 |
$em ->persist( $category ); |
18 |
$em ->persist( $product ); |
19 |
$em -> flush (); |
20 |
return new Response( |
21 |
'Created product id: ' . $product ->getId() |
22 |
. ' and category id: ' . $category ->getId() |
23 |
); |
24 |
} |
25 |
} |
1.3 批量插入函数
01 |
/** |
02 |
* 单词首字母大写(用于set函数) |
03 |
* |
04 |
* @author wyl |
05 |
* @param string $str |
06 |
* @return string |
07 |
*/ |
08 |
function ucWords( $str ) |
09 |
{ |
10 |
$str = ucwords( str_replace ( '_' , ' ' , $str )); |
11 |
$str = str_replace ( ' ' , '' , $str ); |
12 |
return $str ; |
13 |
} |
14 |
|
15 |
/** |
16 |
* 批量写入数据 |
17 |
* |
18 |
* @author wyl |
19 |
* @param string $entity |
20 |
* @param array $dataList |
21 |
* @param array $per |
22 |
*/ |
23 |
function batchInsertByEntity( $entity , $dataList , $per = 1000) |
24 |
{ |
25 |
$count = count ( $dataList ); |
26 |
for ( $i = 0; $i < $count ; $i ++) { |
27 |
$obj = new $entity (); |
28 |
foreach ( $dataList [ $i ] as $k => $v ) { |
29 |
$obj ->{ "set" . $this ->ucWords( $k )}( $v ); |
30 |
} |
31 |
$this ->em->persist( $obj ); |
32 |
if (( $count % $per ) === 0) { |
33 |
$this ->em-> flush (); |
34 |
$this ->em->clear(); |
35 |
} |
36 |
} |
37 |
// 除不尽剩下的还是要保存的 |
38 |
$this ->em-> flush (); |
39 |
$this ->em->clear(); |
40 |
} |
(2)删除记录:
01 |
public function deleteAction( $id ) |
02 |
{ |
03 |
$em = $this ->getDoctrine()->getManager(); |
04 |
$product = $em ->getRepository( 'AcmeStoreBundle:Product' )->find( $id ); |
05 |
|
06 |
if (! $product ) { |
07 |
throw $this ->createNotFoundException( |
08 |
'No product found for id ' . $id |
09 |
); |
10 |
} |
11 |
|
12 |
$em ->remove( $product ); //注意:此处是remove函数 |
13 |
$em -> flush (); |
14 |
return $this ->redirect( $this ->generateUrl( 'homepage' )); |
15 |
} |
(3)查询记录:
参看这篇文章:Symfony2 Doctrine 数据库查询方法总结
Symfony和Doctrine进行了集成,Doctrine类库全部目标就是给你一个强大的工具,让你的工作更加容易。
Doctrine是完全解耦与Symfony的,所以并不一定要使用它。
一个简单例子:一个产品,我们首先来配置数据库,创建一个Product对象,添加到数据库并把它读回来。
首先,我们需要创建一个bundle:
1 |
$php app/console generate:bundle --namespace=Blog/StoreBundle |
一、配置数据库
在开始之前,首先需要配置数据库连接信息。根据惯例,这些信息通常会配置在app/config/parameters.yml 文件中。
01 |
#app/config/parameters.yml |
02 |
# This file is auto-generated during the composer install |
03 |
parameters: |
04 |
mailer_transport: smtp |
05 |
mailer_host: 127.0.0.1 |
06 |
mailer_user: null |
07 |
mailer_password: null |
08 |
locale: zh_CN |
09 |
secret: 256d7de0d269e37752b49fec38f5fc5e |
10 |
debug_toolbar: true |
11 |
debug_redirects: false |
12 |
use_assetic_controller: true |
13 |
database_path: null |
14 |
assets_version: 0 |
15 |
database_driver: pdo_mysql |
16 |
database_host: 127.0.0.1 |
17 |
database_port: 3306 |
18 |
database_name: symfony |
19 |
database_user: root |
20 |
database_password: 123 |
将配置信息定义到parameters.yml文件中也是一个常用的做法。定义在该文件中的配置信息将会被主配置文件在安装Doctrine时引用。
01 |
#app/config/doctrine.yml |
02 |
|
03 |
# Doctrine Configuration |
04 |
doctrine: |
05 |
dbal: |
06 |
default_connection: default |
07 |
connections: |
08 |
default: |
09 |
driver: "%database_driver%" |
10 |
host: "%database_host%" |
11 |
port: "%database_port%" |
12 |
user: "%database_user%" |
13 |
password: "%database_password%" |
14 |
charset: UTF8 |
15 |
dbname: "%database_name%" |
16 |
|
17 |
# if using pdo_sqlite as your database driver, add the path in parameters.yml |
18 |
# e.g. database_path: "%kernel.root_dir%/data/data.db3" |
19 |
# path: "%database_path%" |
20 |
|
21 |
orm: |
22 |
auto_generate_proxy_classes: "%kernel.debug%" |
23 |
#auto_mapping: true |
24 |
entity_managers: |
25 |
default: |
26 |
connection: default |
27 |
mappings: |
28 |
StoreBundle: ~ |
以上文件中dbal和orm中的default均可以复制后更改以实现多个数据库链接。
在config.yml中导入上面的两个yml配置文件:
1 |
#app/config/config.yml |
2 |
|
3 |
imports: |
4 |
- { resource: parameters.yml } |
5 |
- { resource: doctrine.yml } |
6 |
- { resource: security.yml } |
通过把数据库信息分离到一个特定的文件中,你可以很容易的为每个服务器保存不同的版本。现在Doctrine知道你的数据库配置了,你可以用它来创建一个数据库了。
二、创建和生成数据库表结构
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)。
01 |
// src/Blog/StoreBundle/Entity/Product.php |
02 |
|
03 |
namespace Blog\StoreBundle\Entity; |
04 |
|
05 |
class Product |
06 |
{ |
07 |
protected $name ; |
08 |
protected $price ; |
09 |
protected $description ; |
10 |
} |
这样的类经常被称为“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 |
001 |
// src/Blog/StoreBundle/Entity/Product.php |
002 |
|
003 |
<?php |
004 |
|
005 |
namespace Blog\StoreBundle\Entity; |
006 |
|
007 |
use DoctrineORMMapping as ORM; |
008 |
|
009 |
/** |
010 |
* Product |
011 |
* |
012 |
* @ORMTable() |
013 |
* @ORMEntity(repositoryClass="BlogStoreBundleEntityProductRepository") |
014 |
*/ |
015 |
class Product |
016 |
{ |
017 |
/** |
018 |
* @var integer |
019 |
* |
020 |
* @ORMColumn(name="id", type="integer") |
021 |
* @ORMId |
022 |
* @ORMGeneratedValue(strategy="AUTO") |
023 |
*/ |
024 |
private $id ; |
025 |
|
026 |
/** |
027 |
* @var string |
028 |
* |
029 |
* @ORMColumn(name="name", type="string", length=255) |
030 |
*/ |
031 |
private $name ; |
032 |
|
033 |
/** |
034 |
* @var float |
035 |
* |
036 |
* @ORMColumn(name="price", type="float") |
037 |
*/ |
038 |
private $price ; |
039 |
|
040 |
/** |
041 |
* @var string |
042 |
* |
043 |
* @ORMColumn(name="description", type="text") |
044 |
*/ |
045 |
private $description ; |
046 |
|
047 |
|
048 |
/** |
049 |
* Get id |
050 |
* |
051 |
* @return integer |
052 |
*/ |
053 |
public function getId() |
054 |
{ |
055 |
return $this ->id; |
056 |
} |
057 |
|
058 |
/** |
059 |
* Set name |
060 |
* |
061 |
* @param string $name |
062 |
* @return Product |
063 |
*/ |
064 |
public function setName( $name ) |
065 |
{ |
066 |
$this ->name = $name ; |
067 |
|
068 |
return $this ; |
069 |
} |
070 |
|
071 |
/** |
072 |
* Get name |
073 |
* |
074 |
* @return string |
075 |
*/ |
076 |
public function getName() |
077 |
{ |
078 |
return $this ->name; |
079 |
} |
080 |
|
081 |
/** |
082 |
* Set price |
083 |
* |
084 |
* @param float $price |
085 |
* @return Product |
086 |
*/ |
087 |
public function setPrice( $price ) |
088 |
{ |
089 |
$this ->price = $price ; |
090 |
|
091 |
return $this ; |
092 |
} |
093 |
|
094 |
/** |
095 |
* Get price |
096 |
* |
097 |
* @return float |
098 |
*/ |
099 |
public function getPrice() |
100 |
{ |
101 |
return $this ->price; |
102 |
} |
103 |
|
104 |
/** |
105 |
* Set description |
106 |
* |
107 |
* @param string $description |
108 |
* @return Product |
109 |
*/ |
110 |
public function setDescription( $description ) |
111 |
{ |
112 |
$this ->description = $description ; |
113 |
|
114 |
return $this ; |
115 |
} |
116 |
|
117 |
/** |
118 |
* Get description |
119 |
* |
120 |
* @return string |
121 |
*/ |
122 |
public function getDescription() |
123 |
{ |
124 |
return $this ->description; |
125 |
} |
126 |
} |
根据Entity生成数据库:
1 |
php app/console doctrine:schema:update --force --em= "default" |
看到如下提示即为成功:
Updating database schema...
Database schema updated successfully! "1" queries were executed
三、从已有数据库生成Entity
1 |
#生成Entity基础字段: |
2 |
php app/console doctrine:mapping: import --force StoreBundle annotation |
3 |
#根据数据库结构生成Product表的Entity |
4 |
app/console doctrine:mapping: import --em= "default" StoreBundle --filter=Product annotation |
5 |
#生成get/set方法: |
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 |
四、保存数据到数据库
01 |
// src/Blog/TestBundle/Controller/DefaultController.php |
02 |
|
03 |
// ... |
04 |
use Blog\StoreBundle\Entity\Product; |
05 |
|
06 |
use Symfony\Component\HttpFoundation\Response; |
07 |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; |
08 |
|
09 |
// ... |
10 |
public function createAction() |
11 |
{ |
12 |
$product = new Product(); |
13 |
$product ->setName( 'A Foo Bar' ); |
14 |
$product ->setPrice( '19.99' ); |
15 |
$product ->setDescription( 'Lorem ipsum dolor' ); |
16 |
|
17 |
$em = $this ->getDoctrine()->getManager(); |
18 |
|
19 |
$em ->persist( $product ); |
20 |
$em -> flush (); |
21 |
|
22 |
return new Response( 'Created product id ' . $product ->getId()); |
23 |
} |
配置路由:
1 |
#src/Blog/TestBundle/Resources/config/routing.yml |
2 |
|
3 |
test_create: |
4 |
path: / test /create |
5 |
defaults: { _controller: TestBundle:Default:create } |
五、从数据库读取
01 |
public function showAction( $id ) |
02 |
{ |
03 |
$product = $this ->getDoctrine() |
04 |
->getRepository( 'AcmeStoreBundle:Product' ) |
05 |
->find( $id ); |
06 |
if (! $product ){ |
07 |
throw $this ->createNotFoundException( 'No product found for id ' . $id ); |
08 |
} |
09 |
//do something,想把$product对象传递给一个template等。 |
10 |
} |
配置路由:
1 |
#src/Blog/TestBundle/Resources/config/routing.yml |
2 |
|
3 |
test_show: |
4 |
path: /show/{ id } |
5 |
defaults: { _controller: TestBundle:Default:show } |
其他查询方式可参考:Symfony2 Doctrine 数据库查询方法总结
六、更新记录
01 |
public function updateAction( $id ) |
02 |
{ |
03 |
$em = $this ->getDoctrine()->getEntityManager(); |
04 |
$product = $em ->getRepository( 'AcmeStoreBundle:Product' )->find( $id ); |
05 |
|
06 |
if (! $product ) { |
07 |
throw $this ->createNotFoundException( 'No product found for id ' . $id ); |
08 |
} |
09 |
|
10 |
$product ->setName( 'New product name!' ); |
11 |
$em -> flush (); |
12 |
|
13 |
return $this ->redirect( $this ->generateUrl( 'homepage' )); |
14 |
} |
更新记录仅需要三步:
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 |
$em ->remove( $product ); |
2 |
$em -> flush (); |
八、工作笔记记录(可跳过):
1.1 单表增加
01 |
use Acme\StoreBundle\Entity\Product; |
02 |
|
03 |
public function createAction() |
04 |
{ |
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 ); |
11 |
$em -> flush (); |
12 |
return new Response( 'Created product id ' . $product ->getId()); |
13 |
} |
1.2 多表增加
01 |
use Acme\StoreBundle\Entity\Category; |
02 |
use Acme\StoreBundle\Entity\Product; |
03 |
|
04 |
use Symfony\Component\HttpFoundation\Response; |
05 |
class DefaultController extends Controller |
06 |
{ |
07 |
public function createProductAction() |
08 |
{ |
09 |
$category = new Category(); |
10 |
$category ->setName( 'Main Products' ); |
11 |
$product = new Product(); |
12 |
$product ->setName( 'Foo' ); |
13 |
$product ->setPrice(19.99); |
14 |
// relate this product to the category |
15 |
$product ->setCategory( $category ); |
16 |
$em = $this ->getDoctrine()->getManager(); |
17 |
$em ->persist( $category ); |
18 |
$em ->persist( $product ); |
19 |
$em -> flush (); |
20 |
return new Response( |
21 |
'Created product id: ' . $product ->getId() |
22 |
. ' and category id: ' . $category ->getId() |
23 |
); |
24 |
} |
25 |
} |
1.3 批量插入函数
01 |
/** |
02 |
* 单词首字母大写(用于set函数) |
03 |
* |
04 |
* @author wyl |
05 |
* @param string $str |
06 |
* @return string |
07 |
*/ |
08 |
function ucWords( $str ) |
09 |
{ |
10 |
$str = ucwords( str_replace ( '_' , ' ' , $str )); |
11 |
$str = str_replace ( ' ' , '' , $str ); |
12 |
return $str ; |
13 |
} |
14 |
|
15 |
/** |
16 |
* 批量写入数据 |
17 |
* |
18 |
* @author wyl |
19 |
* @param string $entity |
20 |
* @param array $dataList |
21 |
* @param array $per |
22 |
*/ |
23 |
function batchInsertByEntity( $entity , $dataList , $per = 1000) |
24 |
{ |
25 |
$count = count ( $dataList ); |
26 |
for ( $i = 0; $i < $count ; $i ++) { |
27 |
$obj = new $entity (); |
28 |
foreach ( $dataList [ $i ] as $k => $v ) { |
29 |
$obj ->{ "set" . $this ->ucWords( $k )}( $v ); |
30 |
} |
31 |
$this ->em->persist( $obj ); |
32 |
if (( $count % $per ) === 0) { |
33 |
$this ->em-> flush (); |
34 |
$this ->em->clear(); |
35 |
} |
36 |
} |
37 |
// 除不尽剩下的还是要保存的 |
38 |
$this ->em-> flush (); |
39 |
$this ->em->clear(); |
40 |
} |
(2)删除记录:
01 |
public function deleteAction( $id ) |
02 |
{ |
03 |
$em = $this ->getDoctrine()->getManager(); |
04 |
$product = $em ->getRepository( 'AcmeStoreBundle:Product' )->find( $id ); |
05 |
|
06 |
if (! $product ) { |
07 |
throw $this ->createNotFoundException( |
08 |
'No product found for id ' . $id |
09 |
); |
10 |
} |
11 |
|
12 |
$em ->remove( $product ); //注意:此处是remove函数 |
13 |
$em -> flush (); |
14 |
return $this ->redirect( $this ->generateUrl( 'homepage' )); |
15 |
} |
(3)查询记录:
参看这篇文章:Symfony2 Doctrine 数据库查询方法总结