2013-11-28 55 views
5

我想設置爲null,在教義字段更新場,這裏是一句如何學說將其設置爲null

$em = $this->getDoctrine()->getManager(); 
$qb = $em->createQueryBuilder(); 
$query = $qb->update('Model\Example', 'u')->set('u.deletedAt', ':deletedAt') 
->where("u.id IN (:ids)")->setParameter('deletedAt', null) 
->setParameter('ids', $ids) 
->getQuery(); 
$query->execute(); 

我認爲這個代碼應該做的工作,但即時得到這個例外

An exception occurred while executing 'UPDATE example SET deleted_at = ? WHERE (id IN (?)) AND (example.deleted_at IS NULL)' with params [null, "5,6"]: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: la sintaxis de entrada no es válida para integer: «5,6»

首先爲什麼教義是添加AND(example.deleted_at IS NULL)我做錯了什麼?

+0

我認爲錯誤在於「$ IDS」變量,它似乎並不爲數組... – santamanno

回答

0

你必須改變這種

->where("u.id IN (:ids)")->setParameter('deletedAt', null) 

->where($qb->expr()->in('sc.id',$ids)) 
當然$ id的

必須是一個數組,而不是一個字符串。

+0

感謝@DonCastillo那是快如閃電,我改變了一句這個'$查詢= $ QB - > update($ entity_name,'u') - > set('u.deletedAt',':deletedAt') - > where($ qb-> expr() - > in(「u。$ id_name」, $ IDS)) - >的setParameter( 'deletedAt',NULL) - > getQuery();' 但它不是工作,現在它不拋出任何異常,而是建立一個交流中心查詢看看 '更新示例SET deleted_at =? WHERE(id IN('5','6'))AND(例子。deleted_at IS NULL)' 從哪裏學說得到的IS NULL句子? – metalvarez

+0

' - > set('u.deletedAt',':deletedAt')'從這裏開始實際上 – DonCallisto

0

問題是你的$ ids是一個字符串。你可以做:

$arrayOfIds = explode(",", $ids);

在你之後更新查詢:

->setParameter('ids', $arrayOfIds) 
+0

我試過了你的解決方案@Anime,但是教條仍然在建造一個exnge查詢看一看 'UPDATE example SET deleted_at =? WHERE(id IN('5','6'))AND(example.deleted_at IS NULL)'' – metalvarez

5

原始查詢看起來像它應該工作。我複製並測試了:

$em = $this->getService('doctrine.orm.entity_manager'); 
    $qb = $em->createQueryBuilder(); 

    $qb->update('Cerad\Bundle\PersonBundle\Entity\Person','person'); 

    $qb->set('person.verified',':verified'); 
    $qb->setParameter('verified',null); 

    $qb->where('person.id IN (:ids)'); 
    $qb->setParameter('ids',array(1,2,3)); 

    echo $qb->getQuery()->getSql(); // UPDATE persons SET verified = ? WHERE id IN (?) 

    $qb->getQuery()->execute(); 

按預期工作。

您確定要複製/粘貼您的確切代碼嗎?事實後沒有編輯?驗證你的ID數組真的是一個整數數組。這是我可以看到哪裏可能存在問題的唯一地點。確保你的錯誤來自你發佈的代碼。也許其他事情正在發生?嘗試在命令對象中隔離你的代碼。當然,刪除它可以設置爲空嗎?

在這種情況下,沒有必要使用expr對象。 Doctrine 2正確處理IN語句的數組。

====================================

我懷疑你有$ IDS ='5,6'?嘗試將其設置爲:$ ids = array(5,6);雖然即使對於一個字符串,我也沒有看到它是如何搞亂查詢的。

1

謝謝@Cerad問題是我使用了StofDoctrineExtensionsBundle的軟刪除擴展,並且軟件包中添加了軟刪除過濾器,所以我只是禁用了軟刪除過濾器,現在它按預期工作,發佈了許多解決方案謝謝。

$em = $this->getDoctrine()->getManager(); 
$em->getFilters()->disable('softdeleteable'); // this was the problem when you use the soft delete extension you need to disable the filter if you want to reactivate deleted records 
$qb = $em->createQueryBuilder(); 
$qb->update('Model\Example', 'q'); 
$qb->set('q.deletedAt',':deletedAt'); 
$qb->setParameter('deletedAt',null); 
$qb->where("q.id IN (:ids)"); 
$qb->setParameter('ids', $ids);