更新HasMany记录 [英] Update a HasMany records

查看:71
本文介绍了更新HasMany记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个可运行的应用程序从cakephp2转换为cakephp3。我正在努力获取一种可更新hasMany记录的表格。

I am converting a working app from cakephp2 to cakephp3. I'm struggling to get a form that updates hasMany records to work.

该应用具有以下结构:

模型:


MODELS:

use Cake\ORM\Table;
use Cake\Validation\Validator;

class AwardsTable extends Table
{
  public function initialize(array $config)
  {
   $this->hasMany('Levels', ['sort' => 'sort_order']);
  }
}


namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;

class Award extends Entity
{
  protected $_accessible = [
    'name'            =>  true,
    'url'             =>  true,
    'organisation'    => true,
    'detail'          =>  true,
    'logo'            =>  true,
    'levels'          =>  true,
    'Levels'          =>  true
   ];

}

在表单中:

<?= $this->Form->input("levels.$i.name",  'label'=>false,'type'=>'text','value' => $award->name]);?>
<?= $this->Form->input("levels.$i.id", ['value' => $award->id]); ?>

控制器

$this->Awards->patchEntity($award, $this->request->data, ['associated' => ['Levels']]);         
if ($this->Awards->save($award)) {
    $this->Flash->success(__('Your Award has been saved.'));
    $this->redirect(['action' => 'index']);
}

这似乎符合此处的建议: http://book.cakephp.org/3.0/zh/views/helpers/ form.html#associated-form-inputs

This seems inline with what is recommended here: http://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs

我尝试使用大写字母&多元化。奖励数据已正确保存,但相关的级别数据未保存。

I've tried a few variations with capitalisation & pluralisation. The award data saves correctly but the associated levels data does not save.

要保存has_many关联数据,我缺少什么?

What am I missing to get the has_many association data to save?

编辑:示例数据数组提交:

Example Data array submitted:

    2016-01-28 23:32:56 Error: Array
(
    [id] => 4
    [name] => test award
    [organisation] => test org
    [url] => http://www.example.com
    [detail] => 
    [levels] => Array
        (
            [0] => Array
                (
                    [name] => test 1
                    [id] => 4
                )

            [11] => Array
                (
                    [name] => test
                    [id] => 16
                )

        )

    [image] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

)


推荐答案

在LevelEntity中验证'id '是可访问的

In LevelEntity verify if 'id' is accessible

protected $_accessible = [
    '*' => true,
    'id' => true,
];

这篇关于更新HasMany记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆