将sql查询转换为cakephp格式

时间:2012-10-10 15:46:03

标签: sql cakephp

您好

我需要将以下sql查询转换为cakephp find()格式。它自己的查询工作正常,但我需要改变它。

$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"
);  

感谢

1 个答案:

答案 0 :(得分:1)

如果您的关系是订单HABTM部分,并且您有一个表orders_parts,其中包含列:id,order_id,part_id,您应该可以执行以下操作:

首先,获取订单中的部件的ID:

//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
));

现在获取不在订单中的部分:

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