symfony2中mysql和mongodb的增删改查总结
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的增删改查总结的更多相关文章
- Java实现mongodb原生增删改查语句
Java实现mongodb原生增删改查语句 2018-03-16 自动化测试时,需校验数据库数据,为了快速自动化,在代码中用原生增删改查语句操作mongodb 结构 代码 0 pom.xml < ...
- python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)
一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...
- Python进阶----数据库的基础,关系型数据库与非关系型数据库(No SQL:not only sql),mysql数据库语言基础(增删改查,权限设定)
day37 一丶Python进阶----数据库的基础,mysql数据库语言基础(增删改查,权限设定) 什么是数据库: 简称:DataBase ---->DB 数据库即存放数据的仓库, ...
- Java连接MongoDB进行增删改查
1.导入必须的包: 详情看项目:http://pan.baidu.com/s/1cvDAOY 2.通过Myeclipse创建WEB项目 3. 3.bean:创建实体类 package com.bean ...
- MongoDB的增删改查 转
MongoDB的增删改查 (黎明你好原创作品,转载请注明) MongoDB中数据的基本单元叫做文档,采用json的键-值的方式.多个键及其关联的值有序的存放在一起变是文档.类似于编程语言中的键值关系. ...
- Scala对MongoDB的增删改查操作
=========================================== 原文链接: Scala对MongoDB的增删改查操作 转载请注明出处! ==================== ...
- Vc数据库编程基础MySql数据库的表增删改查数据
Vc数据库编程基础MySql数据库的表增删改查数据 一丶表操作命令 1.查看表中所有数据 select * from 表名 2.为表中所有的字段添加数据 insert into 表名( 字段1,字段2 ...
- mysql 的基本操作总结--增删改查
本文只是总结一下mysql 的基本操作,增删改查,以便忘记的时候可以查询一下 1.创建数据库 语法:CREATE DATABASES 数据库名; 例子: CREATE DATABASES studen ...
- 2,MongoDB之增删改查及pymongo的使用
本章我们来学习一下关于 MongoDB的增删改查 一.MongoDB操作 之 原生ORM,根本不存在SQL语句 创建数据库:这里和一般的关系型数据库一样,都要先建立一个自己的数据库空间 是的,Mong ...
随机推荐
- MySQL-18-MHA+Atlas读写分离架构
Atlas介绍 Atlas是由Qihoo 360 Web平台部基础架构团队开发维护的一个基于MySQL协议的数据中间层项目 它是在mysql-proxy 0.8.2版本的基础上,对其进行了优化,增加了 ...
- JVM-超全图
- JVM的GC机制
JVM的GC机制 1. 什么对象会被回收 引用计数法:如果一个对象被引用一次,则记录引用次数加一,如果引用取消,则减一,当减到0时,需要被回收. 问题:循环引用,A引用B,B引用A,除此之外,已经无法 ...
- Lab: 2FA bypass using a brute-force attack:暴力破解双重验证靶场复盘(困难级别)
靶场内容: This lab's two-factor authentication is vulnerable to brute-forcing. You have already obtained ...
- noip8
T1 星际旅行 考试时觉得是道数学题,但没想到忘了欧拉路. 首先将每条边都拆成两条边,那么题目就变成了任意删掉两条边,使得新的图中存在欧拉路.设 \(sum\) 表示自环的数量, \(du_{i}\) ...
- ingress-nginx-controller 部署以及优化
一.说明 本文使用的ingress-nginx v1.0 最新版本,v1.0 适用于 Kubernetes 版本 >= v1.19 小于这个版本的k8s集群,请降级ingress-nginx. ...
- servlet防止表单重复提交
日常开发中,防表单重复提交是一项必须的工作 我们可以利用javascript防止表单重复提交,但是利用javascript防止表单重复提交会出现一个新的问题 因为某些用户可能会绕过script代码直接 ...
- spring开发中常见错误集合,逐步添加
1.关于jstl错误:原因,在jsp页面中使用了jstl标签库,但是却没有导入,可以将相应的jar包放在tomcat的lib目录下,一劳永逸 Java.lang.NoClassDefFoundErro ...
- 怎样在Qt中建立使用动态链接库
参考网址: https://blog.csdn.net/q496713258/article/details/6990837 qt 的学习网址: http://c.biancheng.net/view ...
- offsetof宏---个人笔记
标准库里面提供的offsetof(t,m)宏,用来计算两个变量在内存中的地址偏移量 #include <stdio.h>//原型: #define offsetof(TYPE, MEMBE ...