Symfony4:如何从链接实体接收数据?
Symfony4: How to recieve data from linked entity?
- 订单数//订单数
- 评论//每个订单的评论
我想找到按此顺序写的最新评论。
我的
控制器:
$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".
您正在尝试从另一个实体调用存储库函数
尝试更改此行:
$order->getComments()->findLatest( $order->getId()
与:
$this->getDoctrine()->getRepository(Comments::class)->findLatest($order->getId);
更好的解决方案是使用 $orders->getComments() 数组来避免在循环中从数据库请求数据
您可以使用 class 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();
- 订单数//订单数
- 评论//每个订单的评论
我想找到按此顺序写的最新评论。
我的
控制器:
$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".
您正在尝试从另一个实体调用存储库函数
尝试更改此行:
$order->getComments()->findLatest( $order->getId()
与:
$this->getDoctrine()->getRepository(Comments::class)->findLatest($order->getId);
更好的解决方案是使用 $orders->getComments() 数组来避免在循环中从数据库请求数据
您可以使用 class 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();