【问题标题】:DQL You can't specify target table 'user_addresses' for update in FROM clauseDQL 您不能在 FROM 子句中指定目标表 'user_addresses' 进行更新
【发布时间】:2016-08-25 10:11:39
【问题描述】:

我正在尝试使用连接进行 Doctrine 2 DQL 更新。我已经读到您不能直接执行此操作,而必须使用子查询,这是我目前的代码。

public function unsetNonDefaultBillingAddresses($userId, $userAddressId)
{
    $builder1 = $this->getEntityManager()->createQueryBuilder();
    $subQuery = $builder1->select('a1.userAddressId')
            ->from('Application\Entity\UserAddresses', 'a1')
            ->leftJoin('a1.user', 'u')
            ->where('u.userId = ?1');

    $builder2 = $this->getEntityManager()->createQueryBuilder();
    $builder2->update('Application\Entity\UserAddresses', 'a2')
            ->set('a2.defaultBillingAddress', 0)
            ->where($builder2->expr()->in('a2.userAddressId', $subQuery->getDQL()))
            ->andWhere('a2.userAddressId != ?2')
            ->setParameter(1, $userId)
            ->setParameter(2, $userAddressId);

    \Freedom\Logger\InfoLogger::vardump($builder2->getDQL());
    return $builder2->getQuery()->execute();
}

我正在尝试从 Users 表中更新特定 userId 的 UserAddress 表。这是我的加入代码。

用户表:

/**
 * @var \Doctrine\ORM\PersistentCollection
 *
 * @ORM\OneToMany(targetEntity="Application\Entity\UserAddresses", cascade={"persist", "persist"}, mappedBy="user")
 */
private $addresses;

在我的 UserAddresses 表中:

/**
 * @var \Application\Entity\Users
 *
 * @ORM\ManyToOne(targetEntity="Application\Entity\Users", inversedBy="addresses")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
 * })
 */
private $user;

这是生成的 DQL:

UPDATE Application\Entity\UserAddresses a2
SET a2.defaultBillingAddress = 0
WHERE a2.userAddressId IN
(
    SELECT a1.userAddressId
    FROM Application\Entity\UserAddresses a1
    LEFT JOIN a1.user u
    WHERE u.userId = ?1
) AND a2.userAddressId != ?2

我在其他帖子中看到您必须进行子选择,但我不知道如何在查询生成器中执行此操作。

非常感谢。

【问题讨论】:

  • 我也不知道如何在查询构建器中执行此操作,但您应该从正确且有效的 MySQL 查询开始,然后尝试将其编码到构建器中。

标签: mysql doctrine-orm dql


【解决方案1】:

感谢https://stackoverflow.com/a/15297991/655741,我终于弄明白了如何在 DQL 中做到这一点

这是我的最终代码。

public function unsetNonDefaultBillingAddresses($userId, $userAddressId)
{
    $builder = $this->getEntityManager()->createQueryBuilder();
    $builder->update('Application\Entity\UserAddresses', 'a')
            ->set('a.defaultBillingAddress', 0)
            ->where('a.user = ?1')
            ->setParameter(1, $userId)
            ->andWhere('a.userAddressId != ?2')
            ->setParameter(2, $userAddressId);

    return $builder->getQuery()->execute();
}

a.user 是用户实体的连接,通过将 userId 原则传递给它来完成其余的工作。

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 2013-07-05
    • 2012-12-03
    • 1970-01-01
    • 2016-05-19
    • 2012-03-06
    • 2015-06-08
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多