mysql - DQL 无法在 FROM 子句中指定目标表 'user_addresses' 进行更新

标签 mysql doctrine-orm dql

我正在尝试通过联接进行 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();
}

我正在尝试从“用户”表中更新特定用户 ID 的“用户地址”表。这是我的加入代码。

用户表:

/**
 * @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

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

提前非常感谢。

最佳答案

感谢 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 是到 users 实体的连接,通过向其传递 userId Doctrine 完成了剩下的工作。

关于mysql - DQL 无法在 FROM 子句中指定目标表 'user_addresses' 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36952057/

相关文章:

html - 无需下载即可播放网页中的flv和mkv格式视频

java - 使用jsp形式编辑MYSQL记录

php - 使用 Doctrine 按 FIELD() 排序,这可能吗?

mysql - Doctrine DQL - 预期字符串结尾,得到 'inner'

symfony - 如何在 DQL 中按 NULL 排序?

php - 选择周一到周五之间的日期

MySQL 查询 - 使用 COUNT 的总和

php - 多个 mysql 表 vs 单表设计

doctrine-orm - Symfony2 表单嵌入实体问题

doctrine-orm - Doctrine2 findby 多对一映射