[Dbix-class] Creating rows

Jess Robinson castaway at desert-island.me.uk
Mon Jan 14 12:18:00 GMT 2008



On Mon, 14 Jan 2008, Zbigniew Lukasiak wrote:

> On Jan 5, 2008 7:05 PM, Jess Robinson <castaway at desert-island.me.uk> wrote:
>>
>>
>> On Sat, 5 Jan 2008, Zbigniew Lukasiak wrote:
>>
>>> Happy New Year!
>>>
>>> I've recently learned that in DBIC you can do something like:
>>>
>>> $user_rs->create( { name => 'new nick', addresses => [
>>>            { address => 'new address' },
>>>            { address => 'new address 2' },
>>>            ]
>>>      }
>>> );
>>
>> Funky ain't it, I did that ;)
>>
>>> When refactoring the FormFu::Model::DBIC code I've reached a point
>>> where it would be useful to do:
>>> $user->update_with_relations( { name => 'new nick', addresses => [
>>>            { id => 2, address => 'new home' },
>>>            { id => 3, address => 'new office'},
>>>            { id => undef, address => 'new address'},
>>>            ]
>>>        }
>>>    );
>>> and have the (already existing) related rows updated.  Unfortunately
>>> when I do that DBIC tries to insert them and fails because their ids
>>> are already taken (the last one, with id => undef, works as expected -
>>> a new row is inserted).
>>
>> Not yet, but it's a logical follow on, may be somewhat more interesting to
>> do though.. OTOH nothingmuch has just helped by factoring out a part of
>> the code.
>>
>> new() currently does a find_or_new on all the related bits, then insert()
>> inserts them if needed.
>>
>> update() should likely do similar, plus inserting if new relateds are
>> added. I'm surprised the undef got inserted..
>
> OK - so the updating can be done relatively simply - by just changing
> create_related to update_or_create_related in set_inflated_columns in
> DBIx::Class::Row. The problem is with unrelating the rows that are not
> included in the list.  Should they be deleted or just the foreign key
> should be set to null?
>
> I attach the svn diff (together with test cases).
>
> This was the has_many case - the many_to_many should actually be
> simpler - this will be my next task.


Cool!

Just to recap on conversation in IRC for the benefit of absentees:

It would be useful if this, (like the create multi stuff), did the whole 
lot in a transaction in case there are problems..

Also, we decided to use the state of cascade_delete to decide whether to 
delete the whole lot and replace, or just set the FKs to NULL for the 
unsupplied values.

I also wonder if then add_to_ could be used/revamped to append more 
items.. Does it currently?

Jess



More information about the DBIx-Class mailing list