Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Propel ORM - Joining unrelated tables

Tags:

sql

php

orm

propel

How does this SQL statement translate into Propel (1.6.3)?

SELECT * FROM table_a JOIN table_b

With tableA and tableB sharing no Foreign Keys and having no relationships defined.

TableAQuery::create()->join('tableB')

doesn't work since Propel complains with an error:

"Fatal error: Uncaught exception 'PropelException' with message 'Unknown relation TableB on the TableA table'

Thanks very much in advance for any help and hints! This is my first post here and I hope I haven't done anything wrong yet :-) (I've searched thoroughly before I posted!)

like image 727
Thomas Avatar asked Sep 19 '13 08:09

Thomas


Video Answer


2 Answers

You could also use "addJoin" like this:

TableAQuery::create()
->addJoin(TableAPeer::ThisCOLUMN, TableBPeer::ThatCOLUMN, Criteria::INNER_JOIN); //Can also be left/right

The third argument also takes left and right join.

And, instead of the usual "filterByXXX()"

->filterByOtherColumn(value)

you'd use "add()", like this:

->add(TableAPeer::OtherCOLUMN, value)
like image 148
Qiniso Avatar answered Sep 21 '22 21:09

Qiniso


You can work around this limitation by using raw SQL syntax. For instance:

$con = Propel::getConnection(SomePeer::DATABASE_NAME);
$query = 'SELECT * FROM `table_a` JOIN `table_b` LIMIT 10';
$stmt = $con->prepare($query);
if($stmt->execute()) {
    $res = $stmt->fetchAll();
    var_dump($res);
}

Note #1: These kind of joins can become very big and quickly exhaust the allowed memory size. That's why I've added a LIMIT.

Note #2: The output isn't very clean, arrays of both numeric and associative keys. Maybe there are ways to improve this.

like image 44
twigmac Avatar answered Sep 23 '22 21:09

twigmac