1. 程式人生 > >symfony2中mysql和mongodb的增刪改查總結

symfony2中mysql和mongodb的增刪改查總結

預定義文中用到的變數:

$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’,
))

例題2:

$query = $em->createQuery('SELECT min(bp.price) as minPrice FROM AppBundle:BookPackage bp WHERE bp.bookId=:bookId and bp.status<>2');
$query->setParameter('bookId', $bookId);
return $query->getSingleScalarResult();
例題3、
$goodsIdListString = $this->_getGoodsIdList($materialList);
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT p  FROM AppBundle:Photo p WHERE p.subjectId in ('.$goodsIdListString.') and p.type=1 and p.status=0  ORDER BY p.createTime DESC');
$photoList = $query->getResult();
例題4、
if ($status == InventoryOrder::STATUS_SUBMITTED) {
$index = 'i.submitTime';
} else if ($status == InventoryOrder::STATUS_UNSUBMITTED) {
$index = 'i.createTime';
} else if (empty($status)) {
$index = 'i.createTime';
} else {
throw new \Exception('時間格式不正確', BaseException::ERROR_CODE_ILLEGAL_PARAMETER);
}
$sql = 'SELECT i FROM AppBundle:InventoryOrder i WHERE ';
if(empty($startDate)) {
throw new \Exception('起始時間不為空', BaseException::ERROR_CODE_ILLEGAL_PARAMETER);
}
if (empty($endDate)) {
$endDate = $startDate;
}
$startTimestamp = strtotime($startDate);
$endTimestamp = strtotime($endDate);
if ($startTimestamp > $endTimestamp) {
throw new \Exception('時間引數錯誤', BaseException::ERROR_CODE_ILLEGAL_PARAMETER);
}
$sql .= $index;
$sql .= ' BETWEEN :startDate AND :endDate ';
$start = date('Y-m-d 00:00:00', $startTimestamp);
$end = date('Y-m-d 23:59:59', $endTimestamp);
$params['endDate'] = $end;
$params['startDate'] = $start;
if (!empty($status)) {
$sql .= ' AND i.status = :status';
$params['status'] = $status;
}
$sql .=' ORDER By i.createTime DESC';
$query = $this->entityManager->createQuery($sql);
$orderList = $query->setParameters($params)->getResult();

3.Query Builder查詢
例題1、

$query = $repository->createQueryBuilder(‘p’) ->where(‘p.price > :price’) ->setParameter(‘price’, ’19.99′) ->orderBy(‘p.price’, ‘ASC’) ->getQuery();

$products = $query->getResult();

可以在以下連結中獲取更多的關於查詢生成器的內

例題2、
這其實是一個分頁的查詢
$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();
例題3.使用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();
二、mongodb的操作
 //刪除
     // 刪除掉當前goods下的所有Material
        $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();
 ->multiple(true)這句話的意思,可以刪除所有goodsId==$goodsId的記錄,不加的話,就只刪除第一條資料。
//查詢
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()