symfony2学习几天的总结

request

//获取request    原有的方法$this->getRequest()已经废弃;
$request = $this->container->get('request_stack')->getCurrentRequest();

//获取get参数用(方法参数中注入了参数Request $request时)
$request->query->get();

//获取post参数用
$request->request->get();

创建Bundle

php app/console generate:bundle --namespace=Acme/StoreBundle

从数据库中生成orm.entity实体

//1.生成了orm.yml
app/console doctrine:mapping:import --force WebBundle yml  

//2.生成了entities
php app/console doctrine:mapping:convert annotation ./src

//3.生成了get set方法
app/console doctrine:generate:entities WebBundle --no-backup

# notice 如果要生成EntityRepository.php,需要更改Entity\User.php中
@ORM\Entity(repositoryClass="WebBundle\Entity\UserRepository")

数据库具体操作

查询

1.使用Doctrine’s Query Builder查询对象
$repository = $this->getDoctrine()
    ->getRepository('AppBundle:Product');
 


# more 更多查询语法
//通过主键查询(一般为"id")
$product=$repository->find($id);

//动态方法名基于列值查找
$product=$repository->findOneById($id);
$product=$repository->findOneByProductName('chocolate');

//查询所有产品
$products=$repository->findAall();
//基于任意列值查找一组产品
$products = $repository->findByPrice(19.99);

//按照名字和价格来获取一个匹配的对象(查询条件数组传入)
$product=$repository->findOneBy(array('name'=>'foo','price'=>19.99));

//查询匹配名字的所有产品并按照价格排序
$products = $repository->findBy(
        array('name'=> 'foo'),
        array('price'=>'ASC')
);

$query = $repository->createQueryBuilder('p')
    ->where('p.price > :price')
    ->setParameter('price', '19.99')
    ->orderBy('p.price', 'ASC')
    ->getQuery();
 
$products = $query->getResult();
//该getResult()方法返回一个结果数组
2.使用DQL查询对象
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT p
    FROM AppBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');
 
$products = $query->getResult();

新增

$category = new Category();
$category->setName('Main Products');

$product = new Product();
$product->setName('Foo');
$product->setPrice(19.99);
$product->setDescription('Lorem ipsum dolor');
// relate this product to the category
$product->setCategory($category);

$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->persist($product);
$em->flush();

更新

$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')->find($id);
if (!$product) {
    throw $this->createNotFoundException(
        'No product found for id '.$id
    );
}

$product->setName('New product name!');
$em->flush();

删除

$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')->find($id);
$em->remove($product);
$em->flush();

你可能感兴趣的:(symfony2学习几天的总结)