开发者

How can I do set NULL into the table in Doctrine

I have some table store_section(id,parent_id,label), I want to change some row, set parent_id=null.

I trying to:

$record = $table->getTable()->find( $id );
$record->parent_id = null;
$record->save()开发者_如何学JAVA;

But this isn't work. How can I do set NULL into the table in Doctrine, in example above, parent_id becomes =0 (not =NULL)?

Thnx for the responses!


I would try one of the following:

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();

I have not tested these, but I do recall having a similar issue prior, just cannot recall how I solved it. Hope this helps!


You can use method set('u.name', 'NULL') For example:

Doctrine_Query::create()->update('User u')->set('u.name', 'NULL')->where('u.id = ?',$id);


Doctrine_Null only has two methods, and the one that seems to relate is the __toString method. So in order to activate the magic method you need to cast as a string:

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

But honestly there is no reason, as Doctrine_Null just abstracts an empty string ''. I can only assume that it only works in this scenario because parent_id is not enforcing a NULL attribute.

Setting a value of 'NULL' appears to work but is actually a string and not NULL.

'NULL' !== null

Give it a shot, if you insert 'NULL' into one row, and another row is a "natural NULL", and you pull both rows out of the table and do a var_dump(serialize()) on each, you will see one is a natural null and other is actually a string.

If you want to maintain consistency and enforce natural nulls, use this instead:

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


in this case, when the field is a relation. I have complished this task with:

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

Above Parent is the relation name.


In Doctrine2 Using the query builder, you can also directly update the value in the db.

    $qb = // $this->connection->createQueryBuilder(); or $this->em->createQueryBuilder();
    $qb->update('store_section', 's')
        ->set('s.parent_id', ':parent_id')
        ->andWhere('s.id', ':id'));
    $qb->setParameter('parent_id', null);
    $qb->setParameter('id', $id);
    $qb->execute();


$record->setParentId(null);
$record->save();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜