Tman
Tman

Reputation: 33

converting sql query into cakephp format

Hi

i need the following sql query into cakephp find() format. the query it self is working fine but i need to change it.

$this->Part->query(
    "SELECT `parts`.`id`,`parts`.`part_name` 
     FROM `parts`  
     LEFT JOIN ( 
         SELECT `op` . * 
         FROM `order_parts` AS `op` 
         WHERE `op`.`order_id` =".$this->Session->read('orderid')."
     ) AS `vT` 
     ON ( `parts`.`id` = `vT`.`part_id` )
     WHERE `vT`.`part_id` IS NULL"
);  

thanks

Upvotes: 0

Views: 225

Answers (1)

xSphere
xSphere

Reputation: 86

If your relationship are Order HABTM Part and you have a table orders_parts with columns: id, order_id,part_id you should be able to do something like this:

First, get the ids of the parts which are in the order:

//each Part has one OrdersPart per order
$this->Part->bindModel(array('hasOne' => array('OrdersParts')));
$parts = $this->Part->find('list', array(
  'fields' => array('Part.name'),
  'conditions' => array(
    'OrdersParts.order_id' => $this->Session->read('orderid'),
  ),
  'recursive' => 2
));

Now get the parts which are not in the order:

$this->Part->find('all', array(
  'conditions' => array(
    "NOT" => array('Part.id' => array_keys($parts))
  ),
));

Upvotes: 1

Related Questions