DBICを使っています。
User has_many Histories
っていう関係のテーブルUserとHistoryがあった時に、
Userの行それぞれに対して、最新のHistoryをUserの行の中にキャッシュしておくと便利なときがあります。
そんな時に、$user->add_to_histories ってやった時に $userもupdateしたい、という話です。

CREATE TABLE user (id unsigned not null auto_increment, **中略**, history unsigned not null);
CREATE TABLE history (id unsigned not null auto_increment, user unsigned not null, **中略**, created_date datetime not null);

UserのRowクラスは

package Schema::Row::User;
中略
__PACKAGE__->has_many( histories => 'Schema::Row::History', 'user' );

HistoryのRowクラスは

package Schema::Row::History;
中略
__PACKAGE__->belongs_to( user => 'Schema::Row::User' );

UserのRowクラスに追加されるadd_to_$relを使って

$user->add_to_histories({ action => 'marriage' });  

とかってやるわけです。

HistoryのRowを追加する時にcreated_dateを意識せずに設定したいときとかに、
HistoryのRowクラスに↓って書いておきます

sub insert {
    my $self = shift;
    $self->created_date( DateTime->now ) unless $self->created_date;
    $self->next::method(@_);
    return $self;
}

これはよくやるんですが、同じタイミングでUserの方もupdateしたいって時に、

UserのRowクラスに、

sub create_related {
    my $self = shift;
    my ($rel, $col_data) = @_;
    my $ret = $self->next::method(@_);
    if ( $rel eq 'histories' ) {
        $self->update({ history => $ret->id }); # とか、$col_data->{action} とか
    }
    return $ret;
}

って書いておくと、便利だわー

typester++