ILi*_*cos 101 symfony doctrine-orm
我一直在阅读Doctrine的文档,但是我找不到一种方法来对findAll()结果进行排序.
我正在使用symfony2 + doctrine,这是我在Controller中使用的语句:
$this->getDoctrine()->getRepository('MyBundle:MyTable')->findAll();
但我希望结果按升序用户名排序.
我一直试图以这种方式传递数组作为参数:
findAll( array('username' => 'ASC') );
但它不起作用(它也没有抱怨).
有没有办法在不构建DQL查询的情况下执行此操作?
Pie*_*eau 211
正如@Lighthart所示,是的,它是可能的,虽然它给控制器增加了很多脂肪而且不是DRY.
您应该在实体存储库中真正定义自己的查询,这是简单和最佳实践.
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findAll()
{
return $this->findBy(array(), array('username' => 'ASC'));
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您必须告诉您的实体在存储库中查找查询:
/**
* @ORM\Table(name="User")
* @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
*/
class User
{
...
}
Run Code Online (Sandbox Code Playgroud)
最后,在你的控制器中:
$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();
Run Code Online (Sandbox Code Playgroud)
Sti*_*iig 79
$this->getDoctrine()->getRepository('MyBundle:MyTable')->findBy([], ['username' => 'ASC']);
Run Code Online (Sandbox Code Playgroud)
Dan*_*lci 22
简单:
$this->getDoctrine()->getRepository('AcmeBundle:User')->findBy(
array(),
array('username' => 'ASC')
);
Run Code Online (Sandbox Code Playgroud)
luc*_*nov 20
有时查看源代码很有用.
例如,findAll
实现非常简单(vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php
):
public function findAll()
{
return $this->findBy(array());
}
Run Code Online (Sandbox Code Playgroud)
所以我们看看findBy
并找到我们需要的东西(orderBy
)
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
Run Code Online (Sandbox Code Playgroud)
小智 6
这对我有用:
$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));
Run Code Online (Sandbox Code Playgroud)
保持第一个数组为空取回所有数据,它在我的情况下工作.
小智 6
查看Doctrine API源代码:
class EntityRepository{
...
public function findAll(){
return $this->findBy(array());
}
...
}
Run Code Online (Sandbox Code Playgroud)
您需要使用标准,例如:
<?php
namespace Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;
/**
* Thing controller
*/
class ThingController extends Controller
{
public function thingsAction(Request $request, $id)
{
$ids=explode(',',$id);
$criteria = new Criteria(null, <<DQL ordering expression>>, null, null );
$rep = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
$things = $rep->matching($criteria);
return $this->render('Bundle:Thing:things.html.twig', [
'entities' => $things,
]);
}
}
Run Code Online (Sandbox Code Playgroud)
Symfony 中的 findBy 方法除了两个参数。第一个是要搜索的字段数组,第二个数组是排序字段及其顺序
public function findSorted()
{
return $this->findBy(['name'=>'Jhon'], ['date'=>'DESC']);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
146781 次 |
最近记录: |