在Symfony中传递数据数组

时间:2019-06-13 10:47:38

标签: php arrays symfony-3.4

我在数据库中有我的通知表,我在其中按用户设置所有读取的通知。

目前,此函数仅接收一个ID,但也应该有一个传递ID数组的选项,以便一次将多个ID标记为已读。我需要扩展此函数,以便处理$ this> data ['id']是数组的情况。

我该如何解决?

我的代码:

public function readNotification(User $user, $notificationId)      
{                                                                  

   $notification = $this->getNotificationRepository()->findOneBy([
       'user' => $user,                                           
       'id' => $notificationId                                    
   ]);  

   if($notification) {                                            
       $notification->setRead(new \DateTime());                   
       $this->em->flush();                                        
   }                                                              
}  

我的控制器:

$this->requirePostParams(['id']);
    $this->get('app.service')->readNotification(
        $this->data['user'],
        $this->data['id']
    );

    return $this->success();

1 个答案:

答案 0 :(得分:0)

在现实生活中,获取所有通知并使用flush保存每个通知是一种非常糟糕的方法。假设您的情况是您应该更新1K或更多的通知。这将导致1K更新查询。我建议您创建一个独特的UPDATE查询并在一个查询中更新所有相关项:

UPDATE `tableName` SET `read` = NOW() WHERE id IN (id1, id2, ....)

id1, id2 ...是您要更新的ID的列表。

在您的函数中,您可以执行以下操作:

public function readNotification(User $user, $notificationIds)
{
    if (!is_array($notificationIds)) {
        $notificationIds = [$notificationIds];
    }

    // other code

}