我在Doctrine2中找不到任何有关命名查询的文档。 请帮忙。 Doctrine2是否具有命名查询功能?
答案 0 :(得分:23)
您可以使用
NamedQuery - DQL。实施例
use Doctrine\ORM\Mapping\NamedQuery;
use Doctrine\ORM\Mapping\NamedQueries;
/**
* @Entity
* @Table(name="cms_users")
* @NamedQueries({
* @NamedQuery(name="activated", query="SELECT u FROM __CLASS__ u WHERE u.status = 1")
* })
*/
class CmsUser
{}
并称之为
$this->getDoctrine()->getRepository('MyBundle:CmsUser')
->createNamedQuery('activated')
->getResult();
NamedNativeQuery - SQL。更多信息请访问:http://docs.doctrine-project.org/en/latest/reference/native-sql.html#named-native-query
在EntityRepository中收集查询,例如:
namespace Acme\StoreBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery('SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC')
->getResult();
}
}
此处提供更多信息:http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
此处类似的主题: https://groups.google.com/forum/?fromgroups#!topic/doctrine-user/K-D5ta5tZ3Y[1-25]
答案 1 :(得分:2)
也许您会对EntityRepositories感兴趣,您可以在其中创建和存储复杂的Doctrine查询,并在项目中调用您想要的主题:
http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
答案 2 :(得分:0)
如果您不想搞乱实体定义,可以在存储库的构造函数中调用注释表示法内部使用的函数:
namespace MyBundle\Repository;
use Doctrine\ORM\EntityRepository;
class CmsUserRepository extends EntityRepository
{
public function __construct($em, \Doctrine\ORM\Mapping\ClassMetadata $class)
{
$this->getClassMetadata()->addNamedQuery(array(
'name' => 'activated',
'query' => 'SELECT u FROM __CLASS__ u WHERE u.status = 1'
));
}
}
您还可以使用实体的命名空间和类替换语句的__CLASS__
部分,例如MyBundle\Entity\CmsUser
答案 3 :(得分:0)
我发现这个问题正在寻找Native Named Query示例,上面的答案帮助了我,所以我想我会以同样的方式分享如何进行原生命名查询。
将其添加到实体存储库的构造函数
public function __construct($em, \Doctrine\ORM\Mapping\ClassMetadata $class)
{
parent::__construct($em, $class);
$this->getClassMetadata()->addNamedNativeQuery(
array('name' => 'published',
'query' => 'SELECT
t0.id AS id,
t0.tracking_uri AS tracking_uri,
t0.name AS name,
t0.description AS description,
t0.url_name AS url_name,
t0.status_type_id as status_type_id
FROM
store.store t0
WHERE
t0.status_type_id = 2',
'resultClass' => '__CLASS__',
'resultSetMapping' => array('entities' => array('entityClass' => '__CLASS__',
'fields' => array('id' => 'id',
'tracking_url' => 'tracking_url',
'name' => 'name',
'description' => 'description',
'url_name' => 'url_name',
'status_type' => 'status_type_id')))));
}
这是我对此
的测试的剪辑public function testNamedNativeQueryPublished()
{
$results = $this->em->getRepository('MyBundle:Store')->createNativeNamedQuery('published')->execute();
foreach ($results as $store)
{
$this->assertEquals(2, $store->getStatusType());
}
}