1
votes

I have two tables that should be joined together by a foreign key relationship, unfortunately they are separate into two different database.

My question is that is it possible for me to create a Criteria thingy that allows me to create cross database join query?

1

1 Answers

3
votes

The answer is "no" without doing something exotic. If you look at the source of the Criteria object, it only supports one database name.

You've got two options:

1) Do two queries and do the join yourself. Unless you're very well versed in your particular database, this is the one to go with. Just make sure that each query includes your join field, then foreach over one while you lookup and add from the other.

2) Configure a view or a stored procedure in one database that calls the second database and joins the tables virtually. As far as PHP knows, it's only dealing with one database. I know Oracle can do this -- MySql might be able to, with some expert configuration. (More than my meager skill.)

-- update in response to your comment --

I haven't done this so I don't have sample code. Here's how I'd figure it out. (Off the top of my head, so don't take as gospel...)

Start here with your configuration: http://www.symfony-project.org/book/1_2/08-Inside-the-Model-Layer#chapter_08_database_connections.

Let's say your two connections were named "db1" and "db2".

Supply a database name when creating your criteria object:

$crit1 = new Criteria("db1");
$crit2 = new Criteria("db2");

Do your selects on your two database classes.

$dataOnes = DataOnePeer:doSelect($crit1);
$dataTwos = DataTwoPeer::doSelect($crit2);

Then put them together somehow...

foreach ($dataOnes as $d1) {
    $joinKey = $d1->getMyJoinColumn();
    $d2 = findByKey($dataTwos, $joinKey);
    if (!empty($d2)) {
        $d1->myD2 = $d2;
    }
}

function findByKey($dataTwoArr, $key) {
    foreach($dataTwoArr as $d2) {
        if ($key == $d2->getMyJoinColumn()) {
                return $d2;
        }
    }
    return null;
}

This supposes a 1-1 relationship. You'll have to modify for 1-many.

Good luck!