【问题标题】:Symfony4: How to recieve data from linked entity?Symfony 4:如何从链接实体接收数据?
【发布时间】:2019-05-23 07:53:57
【问题描述】:
  • 订单//订单
  • 评论//每个订单的cmets

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

我的

控制器:

 $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".

【问题讨论】:

  • “不工作”是什么意思?当您调用 getComments 时会发生什么-真正返回的内容是什么?
  • @NicoHaase 感谢您的评论:尝试调用“Doctrine\ORM\PersistentCollection”类的名为“findLatest”的未定义方法。
  • 那么,是什么让您认为可以在集合上调用findLatest?你写过这样的方法吗?

标签: symfony symfony4


【解决方案1】:

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

尝试改变这一行:

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

与:

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

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

【讨论】:

  • 有效!完美的。非常感谢您的支持。我会以这种方式使用它。但是我不清楚为什么它在文档和实体关系创建过程中标记了直接访问它的能力:你想向 Category 添加一个新属性以便你可以访问/更新 getProducts()? (是/否)[是]:>是symfony.com/doc/current/doctrine/associations.html
  • 当然你可以直接访问它,当你执行 $order->getComments() 你会得到所有属于该订单的 cmets。在这种情况下,您可以从数组中获取最后一条评论
【解决方案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();

【讨论】:

  • 感谢您的支持。它看起来非常简单,而且效果很好!
  • @szerz 因为我犯了一个错误,所以我更新了我的答案。我希望它现在运行良好!
  • 谢谢。它完美无缺!感谢您的支持!
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多