Many tables, whether core tables or not, have more than one unique
index. However, if you want to load a row by one of the indices other
than the primary key, you either have to
1) override the JTable::load() method in your table's class (which is
unnecessary considering how simple this patch) or
2) re-write the query (No! Bad! DRY!)
So, I'd like to propose a small change to JTable::load() that won't
break anything currently using it, but will add the ability to load a
JTable object using another index.
Code:
function load( $oid=null, $reset = true, $key=null )
{
if (!empty($key))
{
// Check that $key is field in table
if ( !in_array( $key, array_keys( $this->getProperties() ) ) )
{
$this->setError( get_class( $this ).' does not have the field '.
$key );
return false;
}
$k = $key;
}
else
{
$k = $this->_tbl_key;
}
if ($oid !== null) {
$this->$k = $oid;
}
$oid = $this->$k;
if ($oid === null) {
return false;
}
if ($reset) {
$this->reset();
}
$db =& $this->getDBO();
$query = 'SELECT *'
. ' FROM '.$this->_tbl
. ' WHERE '.$k.' = '.$db->Quote($oid);
$db->setQuery( $query );
if ($result = $db->loadAssoc( ))
{
return $this->bind($result);
}
else
{
$this->setError( $db->getErrorMsg() );
return false;
}
}
Some possible uses for this include (but are not limited to):
1) Checking for existing users with a certain username
2) Checking for existing users with a certain email
3) Any other simple query on an existing JTable object using a key
other than the primary
Example usage:
$user = JTable::getInstance('User', 'JTable');
$user->load('
raf...@dioscouri.com', true, 'email');
(yes, I know that in 1.6 the JTableUser::load() method is overridden,
but it wouldn't take much to change that method too...)
Cheers,
Rafael