我写了一个 api,它有一个函数,通过传递它的 id 将通知设置为已读。
而且,应该有一个选项可以在那里传递 id 数组,以同时将多个标记为已读。我应该扩展函数,以便它处理 $this>data['id'] 是数组的情况。
这是正确的方法吗?
我的服务:
public function read($id = []){
$notification = $this->getRepository()->findBy([
'id' => $id
]);
if($notification) {
$notification[0]->setRead(new \DateTime());
$this->em->flush();
}
}
我的 Controller :
public function readAction()
{
$this->requirePostParams(['id']);
$this->get('app')->read(
$this->data['id']
);
return $this->success();
}
最佳答案
您确实可以将一组 id
值传递给 \Doctrine\ORM\EntityRepository::findBy()
;例如:
$notifications = $this->getRepository()->findBy([
'id' => [1, 2, 3] // etc.
]);
但是,由于 findBy()
可以返回多个结果,它会返回一个数组(或类似数组的对象,如 Doctrine\ORM\PersistentCollection
)。因此,您应该遍历结果集:
foreach ($notifications as $notification) {
$notification->setRead(new \DateTime());
}
$this->em->flush();
此外,这在某种程度上是一个品味问题,但您可能希望使您的 API 更加明确,并为单个操作与一组操作创建单独的方法;例如:
public function read(int $id)
{
//in this scenario you are searching for one notification
// only so you can use `findOneBy()` instead
$notification = $this->getRepository()->findOneBy(['id' => $id]);
$notification->setRead(new \DateTime());
$this->em->flush();
}
public function readMany(array $ids)
{
$notification = $this->getRepository()->findBy(['id' => $ids]);
foreach ($notifications as $notification) {
$notification->setRead(new \DateTime());
}
$this->em->flush();
}
正如@Yoshi 所指出的,read()
也可以巧妙地实现为:
public function read(int $id)
{
$this->readMany([$id]);
}
希望这有帮助:)
关于php - Symfony- 传递一个 id 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54650482/