JTable Best Practice Question

Have a programming question regarding your component, plug-in, extension or core hacks? Have an interesting tidbit, FAQ or programming tip you’d like to share? This is the place for you.

Moderators: tjay, seadap, Rogue4ngel, matthewhayashida

Post Reply
wvteijlingen
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Mon Sep 17, 2007 7:15 pm

JTable Best Practice Question

Post by wvteijlingen » Mon Sep 17, 2007 7:20 pm

Hello,

I'm currently developing a component for Joomla! 1.5. I have a database with a lot of tables, and a lot of them exist of composite primary keys. So far so good. But, as far as i can see from the API docs JTable only accepts one primary key. Now i can override the classes, but i'm wondering what the best practice is.

Thanks in advance,

Wouter

permalink
Joomla! Apprentice
Joomla! Apprentice
Posts: 9
Joined: Tue Feb 19, 2008 5:36 pm

Re: JTable Best Practice Question

Post by permalink » Tue Feb 26, 2008 6:25 am

I generally use an auto increment primary key on tables with composite keys anyways. You can then use store() and delete() when you want to use the id, or you can override if you want to do things like delete a record by the composite key.

Nice thing about this is you can use it to delete all the records with any given 'piece' of your composite, by checking for nulls on one of the values making up your composite. Obviously if you have more than 2 values in your composite, you just add more :)

Code: Select all

function delete($id1, $id2){
	$query = 'DELETE FROM '.$this->getDBO()->nameQuote( $this->_tbl );
	if ($id2 == null){
		//delete all references to a table1 value
		$query .= ' WHERE id1 = '. $id1;
	} else if ($id1 == null){
		//delete all references to a table2 value
		$query .= ' WHERE id2 = '.$id2;
	}else{
		//delete a reference to a composite key join between table1 and table2
		$query .= ' WHERE id1 = '. $id1.' AND id2 = '.$id2;			
	}
	$this->getDBO()->setQuery( $query );

	if ($this->getDBO()->query())	{
			return true;
	}else{
		$this->setError($this->getDBO()->getErrorMsg());
		return false;
	}
}

wvteijlingen
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Mon Sep 17, 2007 7:15 pm

Re: JTable Best Practice Question

Post by wvteijlingen » Tue Feb 26, 2008 10:00 pm

Thanks. Extending the base class with new functionality is of course a normal thing to do in this case.


Post Reply