https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#api

$conn = $this->getDoctrine()->getConnection();
$hasAnswer = $conn->fetchAssoc("SELECT * FROM p_question_answer where testPaperResultId = ? and questionId = ? and type = ?", [$id, $questionId, $type]);
if($hasAnswer) {
$res = $conn->executeQuery("update p_question_answer set con = ? where id = ?", [$con, $hasAnswer['id']]);
} else {
$res = $conn->executeQuery("insert into p_question_answer(`testPaperResultId`,`questionId`,`type`,`create_time`,`con`) value(?, ?, ?, ?, ?)", [$id,$questionId,$type,$nowTime,$con]);
}

生成doctrine 映射关系文件: https://symfony.com/doc/2.3/book/doctrine.html#add-mapping-information

预定义文中用到的变量:

$em = $this->getDoctrine()->getEntityManager();

$repository = $em->getRepository(‘AcmeStoreBundle:Product’);

1.常用的查询

$repository->find($id); //获取的是一条数据
$repository->findAll();  //获取的是数组
$repository->findOneByName(‘Foo’);//获取的是一条数据
$repository->findBy(array(‘name’ => ‘foo’,‘price’ => 19.99),array(‘price’ => ‘ASC’));//获取的是一个数组

2、DQL

例题1.
$query = $em->createQuery(
‘SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC’
)->setParameter(‘price’, ’19.99′); $products = $query->getResult(); 注:
(1) 获得一个结果可以用:$product = $query->getSingleResult(); (2) setParameter(‘price’, ’19.99′);运用这个外部方法来设置查询语句中的 “占位符”price 的值,而不是直接将数值写入查询语句中,有利于防止SQL注入攻击,你也可以设置多个参数: ->setParameters(array(
‘price’ => ’19.99′,
‘name’ => ‘Foo’,
))

3.Query Builder查询

分页的查询
$repository = $this->getDoctrine()
->getRepository('AppBundle:Goods');
$query = $repository->createQueryBuilder('p')
->where('p.name like :name')
->andwhere('p.status = 0')
->setParameter('name', "$fuzzyGoodsInfo")
->orderBy('p.sales', 'DESC')
->setFirstResult($pageSize * $page)
->setMaxResults($pageSize) //相当于limit 取多少条数据 setLimit(100);
->getQuery();
$goodsList = $query->getResult();
例:queryBuilder方法:查询一个数组结果
materialId等于$materialId,并且action在$actionList数组内的。并且按照时间排序
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$resultList = $queryBuilder->select('s')
->from('AppBundle:StockHistory', 's')
->Where('s.materialId = :materialId')
->andWhere($queryBuilder->expr()->in('s.action', $actionList))
->orderBy('s.createTime', 'DESC')
->setParameter('materialId', $materialId)
->getQuery()->getResult();

4.SQL的更新

$query = $em->createQuery("UPDATE AppBundle:ReceiverAddress u SET u.defaultFlag = 0 WHERE u.userId = :userId")->setParameter('userId',$userId);
$result = $query->getResult();

更新一个对象包括三步:

1.从Doctrine取出对象
2.修改对象
3.在实体管理者上调用flush()方法

$em = $this->getDoctrine()->getEntityManager();
$repository = $em
  ->getRepository(‘AcmeStoreBundle:Product’)
  ->find($id);;

if (!$repository) {
  throw $this->createNotFoundException('No product found for id '.$id); 
}
$repository->setName('New product name!'); 
$em->flush();
return $this->redirect($this->generateUrl('homepage'));

5.删除

删除一个对象,需要从实体管理者那里调用remove()方法。

$em->remove($repository); 
$em->flush();

remove()方法告诉Doctrine你想从数据库中移除指定的实体。真正的删除查询没有被真正的执行,直到flush()方法被调用。

6.增加数据

$product = new Product();

$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor'); $em = $this->getDoctrine()->getManager(); $em->persist($product); $em->flush(); $product->getId();

 批量写入例子:

/**
* 批量写入数据
*
*@author wyl
*@param string $entity
*@param array $dataList
*@param array $per
*/ function batchInsertByEntity($entity, $dataList, $per = 1000)
{
$count = count($dataList);
for ($i = 0; $i < $count; $i ++) {
$obj = new $entity();
foreach ($dataList[$i] as $k => $v) {
  $obj->{"set" . $this->ucWords($k)}($v);
}
$this->em->persist($obj);
if (($count % $per) === 0) {
$this->em->flush();
$this->em->clear();
}
} // 除不尽剩下的还是要保存的
$this->em->flush();
$this->em->clear();
}

二、mongodb的操作

更新操作

->multiple(true)这句话的意思,可以删除所有goodsId==$goodsId的记录,不加的话,就只删除第一条数据
// 更新当前goodsId下的所有Material 状态status
$dm = $this->get('doctrine_mongodb')->getManager();
$dm->createQueryBuilder('AppBundle:Material')
    ->update()
    ->multiple(true)
    ->field('status')->set(2)
    ->field('goodsId')->equals($goodsId)
    ->getQuery()
    ->execute(); $dm->flush();
1.根据id直接查询一条记录
$dm = $this->get('doctrine_mongodb')->getManager();
$material = $dm->getRepository('AppBundle:Material')->find(new \MongoId($materialId));

2.往mongodb表中插入一条数据

$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99'); $dm = $this->get('doctrine_mongodb')->getManager();
$dm->persist($product);
$dm->flush();
//定义量   $repository = $this->get('doctrine_mongodb') ->getManager() ->getRepository('AcmeStoreBundle:Product');

1.根据$id查询数据
$product = $repository->find($id);$product = $repository->findOneById($id);$product = $repository->findOneByName('foo');// find *all* products$products = $repository->findAll();$products = $repository->findByPrice(19.99);
$product = $repository->findOneBy(array('name' => 'foo', 'price' => 19.99));
//多个条件查询

$products = $repository->findBy(
array(
'name' => 'foo',
'status' => 0,
),
array('price', 'ASC')
);

//查询一条语句后,更改某个字段的值

$dm = $this->get('doctrine_mongodb')->getManager();
$product = $dm->getRepository('AcmeStoreBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException('No product found for id '.$id);
} $product->setName('New product name!');
$dm->flush();

二、Query Builder查询

$products = $this->get('doctrine_mongodb')
->getManager()
->createQueryBuilder('AcmeStoreBundle:Product')
->field('name')->equals('foo')
->limit(10)
->sort('price', 'ASC')
->getQuery()
->execute()

http://www.xuejiehome.com/blread-1920.html#index_4

symfony2中mysql和mongodb的增删改查总结的更多相关文章

  1. Java实现mongodb原生增删改查语句

    Java实现mongodb原生增删改查语句 2018-03-16 自动化测试时,需校验数据库数据,为了快速自动化,在代码中用原生增删改查语句操作mongodb 结构 代码 0 pom.xml < ...

  2. python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)

    一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...

  3. Python进阶----数据库的基础,关系型数据库与非关系型数据库(No SQL:not only sql),mysql数据库语言基础(增删改查,权限设定)

    day37 一丶Python进阶----数据库的基础,mysql数据库语言基础(增删改查,权限设定) 什么是数据库:    简称:DataBase ---->DB    数据库即存放数据的仓库, ...

  4. Java连接MongoDB进行增删改查

    1.导入必须的包: 详情看项目:http://pan.baidu.com/s/1cvDAOY 2.通过Myeclipse创建WEB项目 3. 3.bean:创建实体类 package com.bean ...

  5. MongoDB的增删改查 转

    MongoDB的增删改查 (黎明你好原创作品,转载请注明) MongoDB中数据的基本单元叫做文档,采用json的键-值的方式.多个键及其关联的值有序的存放在一起变是文档.类似于编程语言中的键值关系. ...

  6. Scala对MongoDB的增删改查操作

    =========================================== 原文链接: Scala对MongoDB的增删改查操作 转载请注明出处! ==================== ...

  7. Vc数据库编程基础MySql数据库的表增删改查数据

    Vc数据库编程基础MySql数据库的表增删改查数据 一丶表操作命令 1.查看表中所有数据 select * from 表名 2.为表中所有的字段添加数据 insert into 表名( 字段1,字段2 ...

  8. mysql 的基本操作总结--增删改查

    本文只是总结一下mysql 的基本操作,增删改查,以便忘记的时候可以查询一下 1.创建数据库 语法:CREATE DATABASES 数据库名; 例子: CREATE DATABASES studen ...

  9. 2,MongoDB之增删改查及pymongo的使用

    本章我们来学习一下关于 MongoDB的增删改查 一.MongoDB操作 之 原生ORM,根本不存在SQL语句 创建数据库:这里和一般的关系型数据库一样,都要先建立一个自己的数据库空间 是的,Mong ...

随机推荐

  1. [.NET大牛之路 007] 详解 .NET 程序集

    .NET大牛之路 • 王亮@精致码农 • 2021.07.13 上一篇我们介绍了 Roslyn 编译器,我们知道,我们编写的 C#/VB 代码经过 Roslyn 编译器编译后会生成程序集文件.按照之前 ...

  2. 面对对象4 Mixins机制 内置方法 反射 异常

    Mixins机制 为什么要有:子类继承父类的时候,可能会碰到需要继承多个父类的情况,那么继承关系也分主类和辅类,既保持主类的功能,也有辅类的功能. 命名方式,我们需要将主类和辅类区分开来,python ...

  3. Ceph 管理和使用

    ceph 管理 上次介绍了Ceph集群架构并且搭建了ceph集群,本节介绍ceph用户认证流程和挂载.cephFS.ceph RBD以及ceph mds高可用 1. ceph 授权流程和用户权限管理 ...

  4. NOIP 模拟 $13\; \text{工业题}$

    题解 本题不用什么推式子,找规律(而且也找不出来) 可以将整个式子看成一个 \(n×m\) 矩阵 考虑 \(f_{i,j}\),它向右走一步给出 \(f_{i,j}×a\) 的贡献,向下走一步给出 \ ...

  5. 题解 P4449 于神之怒加强版

    这道题算是我完完整整推的第一道题,写篇题解纪念一下. 题目 废话不多说,直接开始推式子(给新手准备,过程较详细,大佬可自行跳步),以下过程中均假设 \((n\le m)\),\([d=1]\) 类似于 ...

  6. noip模拟15

    T1 恶心的数学题,还卡空间... 于是考虑数组二次调用,用完memset 记录一手二维前缀和对不同询问离线修改,最后一块回答即可 Code #include<cstdio> #inclu ...

  7. tcp为什么要三次握手,tcp为什么可靠

    转自 : https://www.cnblogs.com/LUO77/p/5771237.html大体看过,没有深入研究,有需要时继续看. 为什么不能两次握手:(防止已失效的连接请求又传送到服务器端, ...

  8. 【spring 注解驱动开发】spring对象的生命周期

    尚学堂spring 注解驱动开发学习笔记之 - 生命周期 生命周期 1.生命周期-@Bean指定初始化和销毁方法 2.生命周期-InitializingBean和DisposableBean 3.生命 ...

  9. Spring parent 属性

    Spring Framework Reference Documentation 6.7. Bean definition inheritance 注:本文中bean和definition意思等同 该 ...

  10. tensorflow 单机多卡 官方cifar10例程

    测试了官方历程,看没有问题,加上时间紧任务重,就不深究了. 官方tutorials:https://www.tensorflow.org/tutorials/images/deep_cnn githu ...