【问题标题】:Access to Doctrine in Entity在实体中访问学说
【发布时间】:2023-03-18 07:35:01
【问题描述】:

我有两个 Entity 类:House 和 Car。

在实体屋类中我有方法:

<?php

namespace Acme\HouseBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * House
 */
class House {
//...
  public function getRandomCar()
  {
      $em = $this->getDoctrine()->getManager();
      $car = $em->getRepository('AcmeCarBundle:Car')->find(rand(0,100));

      return $car->getName();
  }
}

但我无法在我的 Entity House 课程中使用 Doctrine。我该怎么做呢?

【问题讨论】:

  • 在存储库类中执行此操作。
  • 我知道,但是我如何在 Entity 和其他类中使用 Doctrine?

标签: php symfony doctrine-orm sonata-admin symfony-sonata


【解决方案1】:

您需要在CarRepository 中编写函数getRandomCar(您必须创建它)

一个简单的规则是永远不要在实体(汽车、房子......)中编写查询

阅读更多关于Repositories

Car.php

/**
 * @ORM\Table(name="car")
 * @ORM\Entity(repositoryClass="Acme\CarBundle\Entity\CarRepository")
 */
class Car 
{
}

CarRepository.php

class CarRepository extends EntityRepository  
{
    public function getRandomCar() 
    {
        $qb = $this->createQuery('c');
        $qb->where('c.id = :id')
            ->setParameters(array('id' => rand(0,100)))
            ->getQuery();

        return $qb->execute();
    }
}

然后在你的Controller

$em = $this->getDoctrine()->getManager();
$car = $em->$em->getRepository('AcmeCarBundle:Car')->getRandomCar();
$car->getName();

【讨论】:

  • 好的,谢谢,但是我如何在实体和其他类中使用 Doctrine?这不可能吗?
  • 阅读我的回复,您不能也不应该在您的实体中使用原则实体管理器。因此,您可以在控制器和所有其他类(服务...)中使用它,但不能在实体类中使用它
  • 但我不使用控制器。我想在 Sonata Admin 中使用这个方法
猜你喜欢
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多