【问题标题】:Symfony 2 - Doctrine 2 - Native Sql - Delete QuerySymfony 2 - Doctrine 2 - Native Sql - 删除查询
【发布时间】:2014-01-26 20:19:04
【问题描述】:

而不是用

一个一个地删除我的实体
$this->em->remove($price);

我想执行一个原生 SQL 查询来删除我的所有实体。

这是我尝试过的:

$sqlQuery = "delete from mytable where mytable.fieldone_id = ".$fieldoneid." and mytable.fieldtwo_id = ".$fieldtwoid.";";

$query = $this->getEntityManager()->createNativeQuery($sqlQuery);

$query->execute();

它返回以下错误:

Catchable fatal error: Argument 2 passed to Doctrine\ORM\EntityManager::createNativeQuery() must be an instance of Doctrine\ORM\Query\ResultSetMapping, none given

它要我传递一个ResultSetMapping,但它是一个删除查询...

谁能教教我怎么做?

【问题讨论】:

    标签: php sql database symfony doctrine-orm


    【解决方案1】:

    在我看来,我使用了一种不同的方式来执行本机 SQL 查询,这种方式要容易得多。试试这样的(我也在使用PDO方法在查询中包含变量,这样更安全):

    $sql = "delete from mytable where mytable.fieldone_id = :fieldoneid and mytable.fieldtwo_id = :fieldtwoid";
    $params = array('fieldoneid'=>$fieldoneid, 'fieldtwoid'=>$fieldtwoid);
    
    $em = $this->getDoctrine()->getManager();
    $stmt = $em->getConnection()->prepare($sql);
    $stmt->execute($params);
    // if you are doing a select query, fetch the results like this:
    // $result = $stmt->fetchAll();
    

    这对我很有用,希望对你有帮助

    【讨论】:

    • 你刚刚救了我:) 谢谢
    • 在 $params 中传递数组失败并出现错误“注意:数组到字符串的转换”(使用原则 2.5.14)。我不能使用诸如“从表中删除(:id)中的id”之类的语句并将数组传递给“id”。我必须构建完整的 sql 语句“从表中删除 id in (".implode(",",$id).")"。
    【解决方案2】:

    根据Doctrine 2 Native SQL documentation page:

    如果要执行 DELETE、UPDATE 或 INSERT 语句,则不能使用 Native SQL API,并且可能会抛出错误。

    您可以改为使用 DQL 查询。

    $query = $em->createQuery("DELETE FROM YourNamespace\YourBundle\Entity\YourEntity e WHERE e.fieldone_id = " .$fieldoneid . " AND e.fieldtwo_id = " . $fieldtwoid);
    $query->execute();
    

    【讨论】:

    • Native SQL API 与执行原始 SQL 非常不同(这看起来像这里的目标)。任何阅读本文的人,不要将此答案解释为您无法执行原始 SQL。 DQL 也很好,但有时我需要运行对 DQL 来说过于复杂的查询,所以原始 SQL 是唯一的方法。
    【解决方案3】:

    如果想在学说中使用原生方式,可以在实体仓库中使用:

    public function deleteUserNative(User $user): void
    {
        $this->getEntityManager()->getConnection()->delete('user', array('id' => $user->getId()));
    }
    

    只需在你的控制器中调用它:

    $em->getRepository(User::class)->deleteUserNative($user);
    

    问候,

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 2013-03-11
      • 2023-03-09
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      相关资源
      最近更新 更多