Question

I've got a problem converting a my sql query into a propel query.

The query looks like (I already asked for this query before: Changing a sql query using join instead of a subselect )

SELECT cr.* 
FROM confirmation_requests cr
LEFT JOIN confirmations c ON (cr.id = c.confirmation_request_id AND c.device_id = 1)
WHERE c.id IS NULL;

So I tried to transfer this query to propel, which looks like the following:

$confirmationRequests = ConfirmationRequestQuery::create()
                    ->leftJoin("Confirmation c")
                        ->addJoinCondition("c","c.device_id = ?",$device->getId())
                    ->where("c.id IS NULL")
                    ->find();

But it doesn't work.

The sql query from this propel query:

SELECT confirmation_requests.id, 
    confirmation_requests.customer_id, 
    confirmation_requests.confirmation_type_id, 
    confirmation_requests.file_path, 
    confirmation_requests.user_id, 
    confirmation_requests.state, 
    confirmation_requests.created_at, 
    confirmation_requests.updated_at 
FROM `confirmation_requests` 
CROSS JOIN `confirmations` LEFT JOIN `confirmations` `c` ON (confirmation_requests.id=c.confirmation_request_id AND confirmations.user_id = 10) 
WHERE confirmations.id IS NULL
Was it helpful?

Solution

Propel likes to have the table relationships defined in the Schema file, so, begin with your schema files and create a foreign key relationship (add options depending on the type of relationship that exists in the data):

<table name='confirmation_request' ...
  <column name='id' ....
  ...
</table>

<table name='confirmation' ...
  ...
  <column name='cr_id' ...
  <foreign-key foreignTable='confirmation_request' ...
    <reference local='cr_id' foreign='id' ...
  </foreign-key>
  ...
</table>

Then you can write queries like:

$crs = ConfirmationRequestQuery::create()
        ->join('ConfirmationRequest.Confirmation')
        ->where('Confirmation.UserId = 10')    // Add other conditions as required
        ->where('Confirmation.DeviceId = ?', $define->getId())
        ->where('Confirmation.Id IS NULL')
        ->find();

OTHER TIPS

Propel always gives you the fallback to write SQL code, see Answer #2 in http://propelorm.org/blog/2011/02/02/how-can-i-write-this-query-using-an-orm-.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top