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,
    ];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装