Symfony4:如何从链接实体接收数据?

时间:2019-05-23 07:53:58

标签: symfony symfony4

  • 订单 //订单
  • 评论 //每个订单的评论

我想查找以此顺序写的最新评论。

我的

控制器:

 $orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();

  foreach($orders as $order) {  
     $temp = array(
         $order->getId(),
         $order->getComments()->findLatest( $order->getId() ) 

实体(评论):

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Orders", inversedBy="comments")
 */
private $orders;

实体(订单):

/**
 * @return Collection|Comment[]
 */
public function getComments(): Collection
{
    return $this->comments;
}

评论存储库:

public function findLatest($value)
{
    return $this->createQueryBuilder('c')
        ->andWhere('c.orders = :val')
        ->setParameter('val', $value)
        ->orderBy('c.id', 'DESC')
        ->setMaxResults(1)
        ->getQuery()
        ->getResult()
    ;
}

但是看起来它不能以这种方式工作:(

错误:

Attempted to call an undefined method
named "findLatest" of class "Doctrine\ORM\PersistentCollection".

2 个答案:

答案 0 :(得分:2)

您正试图从另一个实体调用存储库函数

尝试更改此行:

 $order->getComments()->findLatest( $order->getId() 

具有:

 $this->getDoctrine()->getRepository(Comments::class)->findLatest($order->getId);

更好的解决方案是,您可以使用$ orders-> getComments()数组来避免在循环内从数据库请求数据

答案 1 :(得分:2)

您可以使用类Doctrine\Common\Collections\Criteria进行此操作。

实体(订单):

use Doctrine\Common\Collections\Criteria;

...

  /**
   * Returns the latest comment or false if no comments found under that criteria
   */ 
  public function findLatestComment()
  {
    $criteria = Criteria::create()
      ->orderBy(array("id" => Criteria::DESC))
    ;

    return $this->getComments()->matching($criteria)->first();
  }

然后您可以像这样简单地使用它:

$order->findLatestComment();