gpt4 book ai didi

symfony - 如何在 DataFixture 类中执行学说查询?

转载 作者:行者123 更新时间:2023-12-04 10:39:39 26 4
gpt4 key购买 nike

如何访问 EntityManager 或 DataFixture 中的存储库类以创建查询?

最佳答案

如果您的夹具实现 ContainerAwareInterface您可以完全访问容器,并且可以从那里获取您的实体管理器之一。

拥有实体管理器后,您可以获取存储库或使用 DQL 或查询构建器创建查询。

namespace Vendor\YourBundleBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadCharacterData implements FixtureInterface, ContainerAwareInterface
{
private $container;

public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}

public function load()
{
$em = $this->container->get('doctrine')->getEntityManager('default');

// example using DQL
$query = $em->createQuery('SELECT u FROM YourBundle\Entity\User u WHERE u.name = your_name');
$users = $query->getResult();

// example query using repository
$repository = $em->getRepository('YourBundle:User');
$entities = $repository->findBy(array('name' => 'your_name'));

// example using queryBuilder
$qb = $repository->createQueryBuilder('u');
$qb
->where('u.name = :name')
->setParameter('name', 'your_name')
->orderBy('u.name');

$users = $qb->getQuery()->getResult();

// ...

}

关于symfony - 如何在 DataFixture 类中执行学说查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17993989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com