如何识别记录是否已找到或创建:class::dbi find_or_create

发布于 2024-11-26 20:57:09 字数 450 浏览 1 评论 0原文

我仍在学习 Perl 和 CLASS::DBI。我有一个执行大量查找的脚本,我只想插入查找找到的新项目。我为 username,created_at 创建了一个复合键,并使用以下代码将其插入到表中。

一切正常,但我想知道是否找到了该记录或是否创建了该记录。我怀疑有一种简单的方法可以做到这一点,但显然我不知道要搜索的正确术语。

请帮忙。

谢谢!

eval {
    FEED::COLLECTION->find_or_create({
        username => $user->{username},
        created_at => $status->{created_at},
        status => $status->{text}
    });
};
if ($@) {
    warn $@;
}

I'm still learning Perl and CLASS::DBI. I have a script that does a bunch of lookups and I only want to insert the new items that are found by the lookups. I created a composite key for username,created_at and I'm using the following code to insert that in to the table.

Everything works, but I would like to know whether the record was found or whether it created the record. I suspect there's an easy way to do this, but apparently I don't know the right terminology to search for.

Please help.

Thanks!

eval {
    FEED::COLLECTION->find_or_create({
        username => $user->{username},
        created_at => $status->{created_at},
        status => $status->{text}
    });
};
if ($@) {
    warn $@;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不吻晚风 2024-12-03 20:57:09

Class::DBI 不记得对象是通过什么途径实例化的,我认为想知道表明一个人问了错误的问题,需要重新表述一个人试图解决的问题。

不过,如果您确实觉得需要知道,请不要使用 find_or_create。它并没有做任何特别聪明的事情;这只是一个方便的例行公事。因此,重新实现它并将该对象注释为已找到:

sub my_find_or_create {
    my $class    = shift;
    my $hash     = ref $_[0] eq "HASH" ? shift: {@_};
    my ($exists) = $class->search($hash);

    if (defined $exists) {
        $exists->{_I_found_this_in_the_back} = 1; # or whatever means of noting preexistence you favor
        return $exists;
    } else {
        return $class->insert($hash);
    }
}

Class::DBI doesn't remember by what route the object was instantiated, and I think that wanting to know suggests that one is asking the wrong question and needs to rephrase the problem one is trying to solve.

If you really feel you need to know, though, don't use find_or_create. It doesn't do anything particularly clever; it's just a convenience routine. So reimplement it and annotate the object as having been found:

sub my_find_or_create {
    my $class    = shift;
    my $hash     = ref $_[0] eq "HASH" ? shift: {@_};
    my ($exists) = $class->search($hash);

    if (defined $exists) {
        $exists->{_I_found_this_in_the_back} = 1; # or whatever means of noting preexistence you favor
        return $exists;
    } else {
        return $class->insert($hash);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文