简体   繁体   English

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

[英]How to identify whether record was found or created: class::dbi find_or_create

I'm still learning Perl and CLASS::DBI. 我仍在学习Perl和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. 我为用户名created_at创建了一个组合键,并且正在使用以下代码将其插入表中。

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 $@;
}

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. Class::DBI不记得实例化对象的方式,我想知道这一点表明一个人提出了错误的问题,需要重新说明一个人试图解决的问题。

If you really feel you need to know, though, don't use find_or_create . 但是,如果您确实需要知道,请不要使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM