我将Symfony4与理论结合使用,试图通过存储库获取数据
我在存储库中有以下查询
public function findByToday($value): ?Clock
{
return $this->createQueryBuilder('c')
->select('c')
->where('c.clockIn BETWEEN :n1days AND :today')
->andWhere('c.status = 0')
->setParameter('today', date('Y-m-d h:i:s'))
->setParameter('n1days', $value)
->getQuery()
->getArrayResult();
}
我的控制器是
public function getToday(ClockRepository $repository)
{
$date = date('Y-m-d h:i:s', strtotime("-1 days"));
$serializer = $this->get('jms_serializer');
$clock = $repository->findByToday($date);
return new Response ($serializer->serialize($clock, "json"));
}
我收到的响应是:“ App \ Repository \ ClockRepository :: findByToday()的返回值必须是App \ Entity \ Clock的实例,或者为null,返回数组(500内部服务器错误)” >
我已经尝试过将函数发送为findByToday(array($ date));或在我的实体构造函数中构建一个新的ArrayCollection。
我因这个错误而错位了。
这是我的实体
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ClockRepository")
*/
class Clock
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
public $clockIn;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
public $clockOut;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="clocks", cascade={"persist"})
*/
private $username;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $status;
public function getId(): ?int
{
return $this->id;
}
public function getClockIn(): ?\DateTimeInterface
{
return $this->clockIn;
}
public function setClockIn(?\DateTimeInterface $clockIn): self
{
$this->clockIn = $clockIn;
return $this;
}
public function getClockOut(): ?\DateTimeInterface
{
return $this->clockOut;
}
public function setClockOut(?\DateTimeInterface $clockOut): self
{
$this->clockOut = $clockOut;
return $this;
}
public function getUsername(): ?User
{
return $this->username;
}
public function setUsername(?User $username): self
{
$this->username = $username;
return $this;
}
public function getStatus(): ?bool
{
return $this->status;
}
public function setStatus(?bool $status): self
{
$this->status = $status;
return $this;
}
}
我做错了什么?
感谢您的帮助。
答案 0 :(得分:0)
我想是我的问题。
控制器中的功能
/**
* @Rest\Get("/v1/clock/today", name="clock_today")
*/
public function getToday(ClockRepository $repository){
$status = false;
$user = $this->getUser();
$date = date('Y-m-d h:i:s', strtotime("-1 days"));
$serializer = $this->get('jms_serializer');
$clock = $repository->findByToday($status, $date, $user);
return new Response ($serializer->serialize($clock, "json"));
}
在我的查询构建器中查询:
public function findByToday($value1, $value2, $value3){
return $this->createQueryBuilder('c')
->where('c.status = :val')
->andWhere('c.clockOut BETWEEN :n1days AND :today')
->andWhere('c.username =:user')
->setParameter('today', date('Y-m-d h:i:s'))
->setParameter('val', $value1)
->setParameter('n1days', $value2)
->setParameter('user', $value3)
->orderBy('c.id', 'ASC')
->setMaxResults(5)
->getQuery()
->getResult();
}
按预期工作。