带和或语句的条件

时间:2011-09-21 09:29:40

标签: sql cakephp

我弄明白了。这是解决方案:

'conditions'=>array(
     'OR' => array(
          array('EavAttribute.attribute_code'=>'lastname'),                            
          array('EavAttribute.attribute_code'=>'firstname')
      ),
     'AND' => array(
          array('UserEntityVarchar.entity_id'=>$id)
     )
)

我正在尝试将此查询转换为cakephp查询,我在条件方面遇到了一些麻烦。无论我如何格式化条件,我总是最终得到下面的第二个查询。

非常感谢任何帮助。

这是我想要复制的查询:

SELECT
    `UserEntityVarchar`.`value_id`,
    `UserEntityVarchar`.`attribute_id`,
    `UserEntityVarchar`.`entity_id`,
    `UserEntityVarchar`.`value`,
    `EavAttribute`.`attribute_code`
FROM
    `user_entity_varchars` AS `UserEntityVarchar`
LEFT JOIN `eav_attributes` AS `EavAttribute` ON(
    `UserEntityVarchar`.`attribute_id` = `EavAttribute`.`attribute_id`)
WHERE
     (UserEntityVarchar.entity_id = 1 AND
     EavAttribute.attribute_code = 'firstname') OR
     (UserEntityVarchar.entity_id = 1 AND
     EavAttribute.attribute_code = 'lastname')

无论我如何格式化我的条件,这都是我不断得到的查询:

SELECT
    `UserEntityVarchar`.`value_id`,
    `UserEntityVarchar`.`attribute_id`,
    `UserEntityVarchar`.`entity_id`,
    `UserEntityVarchar`.`value`,
    `EavAttribute`.`attribute_code`
FROM
    `user_entity_varchars` AS `UserEntityVarchar`
LEFT JOIN `eav_attributes` AS `EavAttribute` ON(
    `UserEntityVarchar`.`attribute_id` = `EavAttribute`.`attribute_id`)
WHERE 
    ((`UserEntityVarchar`.`entity_id` = 1)
AND
    (`EavAttribute`.`attribute_code` = 'firstname'))
AND
    ((`UserEntityVarchar`.`entity_id` = 1)
AND
    (`EavAttribute`.`attribute_code` = 'lastname'))

这是我正在使用的条件:

'conditions'=>array(
    array(
     array('UserEntityVarchar.entity_id'=>$id),
     array('AND ' => array('EavAttribute.attribute_code'=>'firstname'))

    ),
    array('OR' =>
         array('UserEntityVarchar.entity_id'=>$id),
         array('AND ' => array('EavAttribute.attribute_code'=>'firstname'))
    )
)

1 个答案:

答案 0 :(得分:1)

你应该能够这样做:

$this->Model->find('all', array('conditions' => array('OR' => array(

              array('UserEntityVarchar.entity_id' => 1, 
              'EavAttribute.attribute_code' => 'firstname'),

              array('UserEntityVarchar.entity_id' => 1, 
              'EavAttribute.attribute_code' => 'lastname')))));