Query Builder in action

Posted on 2005-05-19 19:10:58 EEST.

Thanks to Jukka's efforts, we have already working MidgardQueryBuilder.

Let's start with simple example.

/* Define which MgdSchema type should be used and returned by QB */
$qb = new midgardquerybuilder("NewMidgardArticle");

/* Define constraints */
$qb->addConstraint("topic", "<", 2);
$qb->addConstraint("title", "=", "News");

/* Execute SQL query and return array*/
$f = $qb->execute();
MySQL query executed:
SELECT article.id FROM article_i,article 
WHERE
article.topic < 2 AND article_i.title = 'News'
AND article.id=article_i.sid

As you notice, title property is defined in article_i table while topic property is defined in article table.
Query Builder follows class' tables definition and is able to search for objects which has more than one table as storage.
$qb->execute(); returned array with only one object ( due to record returned by SELECT ), so

print_r($f[0]);

NewMidgardArticle Object
(
[sitegroup] => 0
[author] => 0
[owner] => 0
[realm] => article
[guid] => cedda8cb461c9f846c73f043aaf888e9
[changed] =>
[updated] =>
[action] => create
[errno] => 0
[errstr] =>
[id] => 28
[calstart] => 0000-00-00
etc etc etc

Let's try to use datetime fields:

$qb = new midgardquerybuilder("NewMidgardArticle");
$qb->addConstraint("revised", ">", "2003-04-30 09:46:00");
$f = $qb->execute();
MySQL query executed:
SELECT article.id FROM article_i,article 
WHERE
article.revised > '2003-04-30 09:46:00'
AND article.id=article_i.sid

Now $qb->execute() returned array with 5 objects. I do not want to print'em all , so let's look at revised properties
if were selected correctly:

print_r($f);
Array(
    [0] => NewMidgardArticle Object
(
[revised] => 2003-04-30 10:30:06
   [1] => NewMidgardArticle Object
(
[revised] => 2003-04-30 10:01:18

[2] => NewMidgardArticle Object
(
[revised] => 2003-04-30 11:03:31
   [3] => NewMidgardArticle Object
(
[revised] => 2005-04-05 16:29:16
    [4] => NewMidgardArticle Object
(
[revised] => 2005-05-12 12:36:18

Simple , fast and usefull :)

OK, now try to read about classes which extend MgdSchema classes and think how this could be used with Query Builder. PHP classes names are not case-sensitive, and MgdSchema type's names are. So if we could use only lowercases for type and classes names in MgdSchema we could extend MgdSchema classes and use own classes and objects with Query Builder too.

Just like this:

class Amerigard extends NewMidgardArticle
{
}
class FlyHigh extends Amerigard
{
}
$qb = new midgardquerybuilder("FlyHigh");
$qb->addConstraint("topic", "<", 2);
$qb->addConstraint("title", "=", "News");

$f = $qb->execute();
MySQL query executed:
SELECT article.id FROM
article_i,article
WHERE
article.topic < 2
AND article_i.title = 'News'
AND article.id=article_i.sid

Above example is not working example of course , but could be :)

Back

Layout Copyright © 2006 Finnish Teleservice Center Ltd Oy - Site Powered by Midgard CMS