[英]doctrine dbal querybuilder as prepared statement
我正在嘗試創建一個 Doctrine DBAL 查詢構建器對象並在其中設置一個參數。 (使用 postgres 數據庫,dbal 2.3.4,學說
$connection = $this->_em->getConnection();
$qb = $connection->createQueryBuilder();
$qb->select('tbl_user_contract.pkid AS pkid');
$qb->from('tbl_user_contract', 'tbl_user_contract');
$qb->join('tbl_user_contract', 'tbl_user', 'tbl_user', 'tbl_user_contract.fk_user = tbl_user.pkid');
$qb->where('tbl_user.pkid = :userid');
$qb->setParameter(':userid', 10);
當我嘗試獲取此 querybuilder 對象的結果時,出現以下錯誤:
SQLSTATE[08P01]: <<Unknown error>>: 7 ERROR: bind message supplies 0 parameters,
but prepared statement "pdo_stmt_00000002" requires 1
當我檢查 postgres 日志時,我看到查詢通過,我注意到它需要一個參數,但我不會得到傳入的參數。
我試圖在 where 表達式本身中設置 id(不使用准備好的語句),這有效。 但我真的很想使用准備好的語句來實現這一點。
有誰知道如何解決這個問題?
提前致謝
我認為你只需要從setparameter
命令中刪除冒號
$qb->setParameter('userid', 10);
至少它適用於 Doctrine 幫助https://www.doctrine-project.org/projects/doctrine-dbal/en/2.9/reference/query-builder.html
您的 querybuilder 函數的 setParameter 部分是錯誤的。 您不需要 :,您可以像這樣將其全部放在一行中,並且只在您的 FROM 語句中包含一個 talbe。 如果有另一個名為 tbl_user 的表並且需要檢查您的實體定義以確保注釋正確,則您的 JOIN 或 FROM 語句中可能有問題。
$connection = $this->_em->getConnection();
$qb = $connection->createQueryBuilder();
$qb->select('tbl_user_contract.pkid AS pkid')
->from('tbl_user_contract')
->join('tbl_user_contract', 'tbl_user', 'tbl_user', 'tbl_user_contract.fk_user = tbl_user.pkid')
->where('tbl_user.pkid = :userid')
->setParameter('userid', 10);
我在 DBAL 2.5.13 中遇到了同樣的問題。
我正在編寫一個使用 Symfony 組件和 DBAL 的工具,因此沒有entityManager
對象,但由於團隊以前對 Symfony 的了解,為了維護類似的結構,我使用如下方法創建了一個存儲庫類:
public function getAtendimentoRealFromOffline($foo3, $foo4)
{
$query = $this->createQueryBuilder()
->select("foo1, foo2")
->from("bar_table")
->andWhere("foo3 = :foo3")
->andWhere("foo4 = :foo4")
->setParameter(":foo3", $foo3)
->setParameter(":foo4", $foo4);
}
現在,如果你像這樣運行:
$this->connection->fetchAll($query);
它確實會向您顯示錯誤,因為您正在使用連接中的 fetchAll 與您剛剛使用QueryBuilder
創建的語句沒有任何關系。 一種解決方案是使用第二個參數發送參數數組:
$this->connection->fetchAll($query, ["foo3" => "bar3", "foo4" => "bar4"]);
您可以從查詢構建器中刪除setParameters
:
$query = $this->createQueryBuilder()
->select("foo1, foo2")
->from("bar_table")
->andWhere("foo3 = :foo3")
->andWhere("foo4 = :foo4")
文檔中看不到的是QueryBuilder
實際上有一個 execute 方法,然后它確實會使用參數運行,因此您可以:
$query->execute()->fetchAll();
文檔說明您可以執行以下操作:
$queryBuilder
->select('id', 'name')
->from('users')
->where('email = ' . $queryBuilder->createNamedParameter($userInputEmail))
;
試試這個:
$qb->where('tbl_user.pkid = :userid');
$qb->setParameter(':userid', 10);
然后
$params = $qb->getParameters();
$stmt = $connection->prepare($qb->getSQL());
foreach ($params as $key=>$value){
$stmt->bindParam($key,$value);
}
$stmt->execute();
$result = $stmt->fetchAllAssociative();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.