我写了一个带有函数的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();
}
}
我的控制器:
public function readAction()
{
$this->requirePostParams(['id']);
$this->get('app')->read(
$this->data['id']
);
return $this->success();
}
答案 0 :(得分:3)
您确实可以将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]);
}
希望这会有所帮助:)