【问题标题】:updateAll query not working in cakephpupdateAll 查询在 cakephp 中不起作用
【发布时间】:2013-04-29 09:00:52
【问题描述】:

我尝试使用 updateAll 命令更新表格帖子。但我有一个错误。我有 wot 表,即用户和帖子。我的控制器是,

<?php
App::uses('AppModel', 'Model');
class Post extends AppModel {
public $belongsTo = array(
    'User' => array(
        'className'    => 'User',
        'foreignKey'   => 'user_id',
        'fields'    => "User.id,User.name,User.uname"
    )
);
function updatePost($title,$content,$pid){
    $this->updateAll(
        array('Post.title' => $title,'Post.content'=>$content),
        array('Post.id' => $pid)
    );
}
}

?>

错误信息是, “错误:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在 'Post 2, Post.@ 附近使用的正确语法987654323@ =

模型是位于第 1 行的业务类。

"SQL 查询:UPDATE blog.posts AS Post LEFT JOIN blog.users AS User ON (Post.user_id = User7)@8 SET Post.title = test_title, Post.content = 样本正文 WHERE Post.id = 2 "; 如何纠正?

【问题讨论】:

  • 1.用户有很多帖子,在 UserModel 文件中有关系??? 2.检查user_id是否存在于用户表中?
  • 是 id 存在于用户表中,而不是 user_id,posts.user_id=users.id
  • 那很好...像这样更改您的代码并检查 $this->updateAll(array('Post.titile' => '\'' .$title.'\'', 'Post .content'=>'\'' .$content.'\''), array('Post.id' => $pid) );
  • 问题是因为您使用了updateAll(),它不会转义/引用值,请参阅我的答案以获取更多信息。您可能正在寻找Model::save()

标签: jquery cakephp sql-update cakephp-2.0


【解决方案1】:
Try...
$this->updateAll(
        array('Post.title' => "'$title'",'Post.content' => "'$content'"),
        array('Post.id' => $pid)
    );

【讨论】:

    【解决方案2】:

    首先,您没有包含实际的错误消息?我只能看到一个查询?

    但是,我确实看到了一些问题;

    • 您好像有错字; Post.titile 看起来像是 Post.title 的拼写错误

    • CakePHP 中的字段应该指定为 数组,而不是逗号分隔的字符串,所以

          'fields'    => array("User.id", "User.name", "User.uname")
      

    但同样,请显示实际的错误消息和/或您所期望的以及您得到的结果

    此外,如文档中所述,updateAll() 中的字段接受 SQL 表达式,因此应手动引用。见Model::updateAll()

    提示 $fields 数组接受 SQL 表达式。应该使用 >Sanitize::escape() 手动引用文字值。

    因为您似乎正在更新单个帖子,所以在我看来,您正在寻找Model::save()

    见:Saving your data

    更新

    要使用 Model::save() 执行此操作,请将您的 updatePost 方法重写为类似的内容;

    function updatePost($title,$content,$pid){
        $this->save(
            array(
                'Post' => array(
                    'id' => $pid,
                    'title' => $title,
                    'content'=> $content
                )
            )
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多