[PATCH] FS::Record by_key constructor

Ricardo SIGNES rjbs+freeside-devel at icgroup.com
Thu Jun 16 08:42:29 PDT 2005


It's seemed needlessly verbose to write:

  qsearchs('some_table', { 'some_column' => $some_value })

Every time I wanted to get the object for a known primary key, and using
a function intead of a method was also a bit jarring, given the mostly
OO interface.

The attached patch adds a ->by_key method to FS::Record, which can be
used to retrieve a record in a FS::Record by primary key.  Example:

  FS::cust_main->by_key(1); # retrieve customer with custnum 1

-- 
rjbs
-------------- next part --------------
Index: FS/FS/Record.pm
===================================================================
RCS file: /var/lib/cvs/cvsroot/freeside/FS/FS/Record.pm,v
retrieving revision 1.2
diff -u -r1.2 Record.pm
--- a/FS/FS/Record.pm	15 Jun 2005 20:52:50 -0000	1.2
+++ b/FS/FS/Record.pm	16 Jun 2005 15:39:21 -0000
@@ -427,6 +427,26 @@
   return @return;
 }
 
+=item by_key($pkey_value)
+
+This returns the record with the given PK value.  This method is only useful in
+FS::Record subclasses.
+
+=cut
+
+sub by_key {
+  my ($class, $pkey_value) = @_;
+
+  my $table = $class->table or return;
+
+  my $dbdef_table = $dbdef->table($table)
+    or die "No schema for table $table found - ".
+           "do you need to create it or run dbdef-create?";
+  my $pkey = $dbdef_table->primary_key;
+
+  return qsearchs($table, { $pkey => $pkey_value });
+}
+
 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
 
 Experimental JOINed search method.  Using this method, you can execute a


More information about the freeside-devel mailing list