【问题标题】:cakePHP: updating mysql table using WHERE clause with multiple conditionscakePHP:使用具有多个条件的 WHERE 子句更新 mysql 表
【发布时间】:2013-06-11 21:44:00
【问题描述】:

我想用 cakePHP 语法写这个 SQL 语句:

UPDATE students SET status = 'graduated' WHERE age = '23' AND major = 'math';

现在,我试图在蛋糕中做到这一点的方式是

$student->updateAll(  array('Student.status' => "'".$rowdata."'"), 
          array('Student.age' => $current_highest_age,'Student.major' =>
                    "'".$major."'"));

我的变量:$rowdata = 'graduated'; $current_highest_age = 23;和 $major = '数学'。

表格未更新。我的语法有问题吗?感谢您的帮助。

问题更新:

实际上,我发现我的语法错在哪里。蛋糕代码应该是'Student.major' => $major 而不是'Student.major'=>"'".$major."'"

【问题讨论】:

    标签: mysql cakephp cakephp-2.0


    【解决方案1】:

    你是双重转义

    updateAll 期望字段是 SQL 表达式(或简单引用的字符串),但条件不应该是。因此,您现在要生成的查询是:

    UPDATE 
        students
    SET
        status = 'graduated' 
    WHERE 
        age = '23' AND 
        major = '\'math\''
    

    为了防止多余的引号导致语法有效的语句匹配 0 行,只需让 Cake 像其他方法一样为您处理您的条件:

    $student->updateAll(
        array('Student.status' => "'".$rowdata."'"), 
        array(
            'Student.age' => $current_highest_age,
            'Student.major' => $major
        )
    );
    

    【讨论】:

      【解决方案2】:

      更新模型字段的简单方法

      $this->Testing->updateAll(
          array('Testing.door_open_close' => $door_open_close),   // value that is updated                  
          array('Testing.id' => $zoneId)     // condition field of a Model
      );
      

      【讨论】:

        【解决方案3】:
        UPDATE students ...
               ^^^^^^^^--- student WITH an S
        

        v.s.

        array('Student.age')
               ^^^^^^^  - student WITHOUT an S
        

        【讨论】:

        • -1 那是CakePHP convention - 所有查询的格式都是VERB ``table`` as ModelName ...。所有表都是复数,所有模型名称都是单数,所有查询都将表别名为模型名称。
        • 实际上,我发现了我的语法错误的地方。蛋糕代码应该是'Student.major' => $major 而不是'Student.major'=>"'".$major."'"
        猜你喜欢
        • 2012-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多