php - Symfony- 传递一个 id 数组

标签 php symfony doctrine-orm

我写了一个 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/

相关文章:

php - 从类内的函数传递变量并在类外回显

php - 在循环内检查错误并执行查询?

php - Symfony2 : accessing variables defined in config. yml 和 config_*.yml

forms - 如何从 div 切换到 Symfony2 表单的表格布局?

php - 为什么多对多关系为空?

symfony - FosRestBundle 不允许使用方法

php - Laravel 4 如何合并数据库表并按 created_at 对它们进行排序?

php - sql连接单个条目与多个条目表的总和

symfony - VichUploaderBundle - 命名者 : Parent definition does not exist

php - 学说使 :migration throws an error on class name generator