Quote:
irmtfan wrote:
@bumciach:
I am sure 2 simple queries is better than one JOIN.
but I am not sure about that when tables are more than 2 like 3, 4, 5 or more.
if I need to get data from only two tables then, in most cases I use the method you described.
In my experience. The more tables including the use of JOIN is simpler (less code). But I did not do benchmarks.
Quote:
Then it will not help you to reduce queries.
I had something else in mind
Suppouse we have two tables in db
le="color: #000000"><?php CREATE TABLE mod_mymodule_articles ( article_id int(11) unsigned NOT NULL auto_increment, category_id mediumint(8) unsigned NOT NULL default 0, title varchar(50) NOT NULL default '', bodytext TEXT NOT NULL, PRIMARY KEY (article_id) ); CREATE TABLE mod_mymodule_categories ( category_id mediumint(8) unsigned NOT NULL auto_increment, name varchar(50) NOT NULL default '', descr TEXT NOT NULL, PRIMARY KEY (category_id) );
So...
le="color: #000000"><?php class mymoduleArticleHandler extends XoopsPersistableObjectHandler { function &getObjects($args) { $sql = "SELECT t2.name AS category_name, t1.* FROM {$this->table} t1, LEFT JOIN {$this->MODULE_X->getHandler('category')->table} t2 ON t2.category_id = t1.category_id";
We get records from DB by handler, but we access to them by object mymoduleArticle class
le="color: #000000"><?php class mymoduleArticle extends XoopsObject { /** * initialize variables for the object */ function __construct() { $this->initVar("article_id", XOBJ_DTYPE_INT, null, false); $this->initVar("category_id", XOBJ_DTYPE_INT, null, false); $this->initVar("title", XOBJ_DTYPE_TXTBOX, null, false); $this->initVar("bodytext", XOBJ_DTYPE_TXTBOX, null, false); //additional fields eg from other tables $this->initVar("category_name", XOBJ_DTYPE_TXTBOX, null, false); //this is need to get value from JOIN query 'SELECT t2.name AS category_name [...]' } }
Usage:
le="color: #000000"><?php $articles = $article_handler->getObjects( $criteria ); foreach ($articles as $art) { echo $art->getVar('title'); echo $art->getVar('category_name'); }
This is useful especially if in many places (and even in other modules) to get a list of titles with the name of the category. Note that in this scope we don't need all fields from joined table (mod_mymodule_categories).
In other case problably more accurate will be reference to both class (mymoduleArticle and mymoduleCategory) - you still have mymoduleCategory class with defined fields, so does not make sense to duplicate those fields in the mymoduleArticle class.