donglu5235 2015-08-09 14:07
浏览 49
已采纳

PatchEntity忽略Cakephp 3.0中ajax请求的数据

I often use the patchEntity function to hydrate my entity with form data, and it works fine, even with an ajax request.

But when I tried to insert data from an an ajax request with JSON data, patchEntity failed to retrieve the data.

My ajax request is very simple:

var rate = function (user, rate, success, error) {
    $.ajax({
            type: "POST",
            url: baseUrl + 'rate/add',
            data: {
                id: this.id,
                user: user.id
                rate: rate
            },
            dataType: 'json',
            success: success,
            error: error
        });
});

In my Rate controller, my add function looks like:

 public function add()
 {
     if ($this->request->isAjax()) {
        $this->layout = 'ajax';
        $rate = $this->Rate->newEntity();
        if ($this->request->is('post')) {
            $rate = $this->Rate->patchEntity($rate, $this->request->data);
           if ($rate->errors()) {
                $this->set([
                    'status' => 500,
                    'message' => $rate->errors()
                ]);
            } else {
                if ($this->rate->save($rate)) {
                    $this->set([
                        'status' => 200
                    ]);
                } else {
                    $this->set([
                        'status' => 500,
                        'message' => $rate->errors()
                    ]);
                }
            }
            return $this->render('/Ajax/result');
        }
}

This throw an exception:

Cannot insert row, some of the primary key values are missing. Got (, , ), expecting (id, user)

I can save my data using this instead of $this->Rate->patchEntity($rate, $this->request->data);

$rate['id'] = $this->request->data['id'];
$rate['user'] = $this->request->data['user'];
$rate['rate'] = $this->request->data['rate'];

What sort of array do I have to pass to patchEntity function to makes this works?

  • 写回答

1条回答 默认 最新

  • douhao2548 2015-08-10 19:50
    关注

    Thanks to ndm's comment, I've checked the Rate Entity and just removed this part which was automatically generated by bake:

    protected $_accessible = [
        'rate' => true,
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项