2010-09-17 44 views
10

我有一些表store_sectionid,parent_id,label),我想改一些行,設置parent_id = null。我該怎麼辦在表中設置NULL在Doctrine

我想:

$record = $table->getTable()->find($id); 
$record->parent_id = null; 
$record->save(); 

但是,這是不行的。在上面的例子中,我怎麼能在Doctrine的表中設置NULL,parent_id變成了= 0(not = NULL)?

Thnx的迴應!

+0

請問你的表定義指定0作爲'parent_id'的默認值? – BenV 2010-09-17 13:23:14

+0

不,默認值=空NULL – ajile 2010-09-17 13:24:23

回答

12

我會嘗試以下方法之一:

1:

$record = $table->getTable()->find($id); 
$record->parent_id = new Doctrine_Null(); 
$record->save(); 

2:

$record = $table->getTable()->find($id); 
$record->parent_id = "NULL"; 
$record->save(); 

我沒有測試過這些,但我之前記得有一個類似的問題,只是不記得我是如何解決它的。希望這可以幫助!

+2

新Doctrine_Null()在Doctrine 1.2中工作。 – Tom 2011-08-01 19:54:16

+1

Ftr,「NULL」!== NULL。你的第二個解決方案實際上插入了字符串NULL。 – 2016-03-15 17:33:19

1

在這種情況下,當字段是關係。我已完成此任務:

$record->Parent = null; 
$record->save(); 

上面的父項是關係名稱。

5

可以使用方法集( 'u.name', 'NULL') 例如:

Doctrine_Query::create()->update('User u')->set('u.name', 'NULL')->where('u.id = ?',$id); 
0
$record->setParentId(null); 
$record->save(); 
+0

你應該更好的更新你的答案,而不是發佈一個新的答案。 – j0k 2012-07-12 12:46:47

2

Doctrine_Null只有兩個方法,這似乎涉及的一個是__toString方法。因此,爲了激活魔術方法,你需要轉換爲字符串:

$record = $table->getTable()->find($id); 
$record->parent_id = (string) new Doctrine_Null; 
$record->save(); 

但說實話,沒有理由,因爲Doctrine_Null剛剛奪取空字符串''。我只能假設它只適用於這種情況,因爲parent_id沒有強制執行NULL屬性。

設置'NULL'值出現工作,但實際上是一個字符串,而不是NULL。

'NULL' !== null 

給它一個鏡頭,如果你插入「NULL」成一排,而另一行是一個「自然NULL」,和你拉兩行出表,做每一個var_dump(serialize()),你會看到一個是自然的null,其他的實際上是一個字符串。

如果你想保持一致性和執行自然​​空值,而不是使用:

$record = $table->getTable()->find($id); 
$record->parent_id = new Doctrine_Expression('NULL'); 
$record->save(); 
+0

在Doctrine 1.2中所有解決方案都失敗的情況下,新的Doctrine_Expression('NULL')似乎實際上運行得非常好。感謝您節省我的一天。 – TwystO 2017-02-24 10:53:39