保存来自 hasMany 和 belong To 的数据



我目前在使用cakephp时遇到了一些问题。我已经尝试在这个论坛上找到答案,但就我而言,没有什么真正有用的:(这是我的问题:

我有2张桌子:

Author  | Role
id      | id
role_id | name

我将作者设置为"属于角色",将我的角色设置为"拥有许多作者"

在我看来,我的表格看起来像这样:

$this->Form->create('Role')
$this->Form->input('name'));
$this->Form->input('Author.id', array('type' => 'select', 'multiple' => true, 'options' => $authors));

我的角色控制器:

function index() {
    if (!empty($this->data)) {
        if ($this->Role->saveAll($this->data)) {
        }
    }
    $this->set('authors', $this->Role->Author->find('list'));
}

但是当我尝试保存时,我的新角色创建得很好,但它也会创建一个新的作者行而不是更新现有的作者行。我想要的只是在创建新角色时更新"作者"表中的role_id。知道怎么了?

编辑:我也得到相同的结果 $this->请求>数据而不是 $this>数据当我创建一个分配有 2 位作者的新角色时,我的数据如下所示:

array(
    'Role' => array(
        'name' => 'test',
    ),
    'Author' => array(
        'id' => array(
            (int) 0 => '1',
            (int) 1 => '3'
        )
    )
)

感谢您的帮助。

首先,保存数据的格式不正确。您不能将Author.id设置为数组,它需要一个整数,因此不会更新现有数据。

不是100%确定这会起作用,但请尝试像这样重写保存数据:-

$authorIds = Hash::extract($this->request->data, 'Author.id.{n}');
foreach ($authorIds as $authorId) {
    $authors[] = [
        'id' => $authorId
    ];
}
$data = [
    'Role' => $this->request->data['Role'],
    'Author' => $authors
];

然后使用 $this->Role->saveAll($data) .(我相信有一种更优雅的编写方式,只是一些快速的示例代码)。

相关内容

最新更新