Iwould Preferanon Tue Jun 22 23:25:46 -0400 2010

Subject: Setting an INT column to NULL (foreign key)

I have a model with a NULLable foreign key reference called parent_id. I'm having an issue actually NULLing the value once it has been set (via an update). I just use (and this is shortened to not include any error checking):

$obj = User::find (1);
$obj->parent_id = NULL; // (note that parent_id was originally a valid value).
$obj->save ().

But the object never gets saved to the database for some reason (i.e. the value of parent_id is not changed). Is there something I need to do to set this to NULL?

Kien La Wed Jun 23 13:46:06 -0400 2010

It's working as intended for me. What version are you using? Have you tried the latest version?

kirk bushell Wed Jun 23 23:27:55 -0400 2010

I have experienced this problem also. Specifically relating to an integer field that has allows null values. If I do not populate the field it defaults to 0 (even though that is not the case for the table).

Kien La Thu Jun 24 00:50:17 -0400 2010

Not able to reproduce either problem

create table foos(id int not null primary key auto_increment, 
name varchar(10),
parent_id int);

class Foo extends ActiveRecord\Model {}

mysql> select * from foos;
| id | name | parent_id |
|  1 | NULL |      NULL |

$foo = Foo::find(1);
$foo->name = 'test';
$foo->parent_id = null;

mysql> select * from foos;
| id | name | parent_id |
|  1 | test |      NULL |

It's null in both cases.

kirk bushell Thu Jun 24 00:52:12 -0400 2010

Kien - what is the result when you do not explicitly set the value to null?

Kien La Thu Jun 24 00:57:29 -0400 2010

Still saves as null. Same results if I uncomment flag_dirty

1 $foo = Foo::find(1);
2 $foo->name = 'test';
3 #$foo->parent_id = null;
4 #$foo->flag_dirty('parent_id');
5 $foo->save();
Iwould Preferanon Thu Jun 24 15:40:49 -0400 2010

I will try the latest build tonight. What is currently happening is that once the foreign key is established (i.e. it is set to a non-NULL value), it can no longer be set back to NULL. Maybe I'm doing something else wrong, but I'll check into it tonight to be sure. I could try setting the dirty flag too to see if that changes things.

Iwould Preferanon Thu Jun 24 15:48:19 -0400 2010

It works, and it was completely my fault (my apologies for wasting your time). Suffice to say:

"Sometimes case sensitivity can be a bitch."


Kien La Thu Jun 24 15:50:19 -0400 2010

No worries. Glad it's working for you.