【问题标题】:PatchEntity ignore data from an ajax request in Cakephp 3.0PatchEntity 在 Cakephp 3.0 中忽略来自 ajax 请求的数据
【发布时间】:2015-08-09 14:07:24
【问题描述】:

我经常使用patchEntity 函数将我的实体与表单数据结合起来,它工作正常,即使是 ajax 请求。

但是当我尝试从带有 JSON 数据的 ajax 请求中插入数据时,patchEntity 无法检索数据。

我的ajax请求很简单:

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
        });
});

在我的速率控制器中,我的添加函数如下所示:

 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');
        }
}

这会引发异常:

无法插入行,缺少一些主键值。拿到 (, , ), 期望 (id, user)

我可以用这个代替$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'];

我必须将什么样的数组传递给patchEntity 函数才能使其正常工作?

【问题讨论】:

  • 请出示您的Rate实体代码。此外,每当您收到错误时,请发布 exact 错误消息并包括相关的堆栈跟踪!

标签: php cakephp orm entity cakephp-3.0


【解决方案1】:

感谢 ndm 的评论,我检查了 Rate Entity 并删除了这个由 bake 自动生成的部分:

protected $_accessible = [
    'rate' => true,
];

【讨论】:

    猜你喜欢
    • 2014-02-14
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    相关资源
    最近更新 更多