CakePHP: How to update multiple records at the same time with the Form helper

笑着哭i 提交于 2019-12-03 08:39:42

CakePHP associates all fields with the same 'index' to be a single 'record' in your database. The 'index' (i.e. the 0 in Foo.0.id) does not have any relation to the 'id' of the record, it's just a number.

For example;

Foo.0.id   = 123
Foo.0.name = 'hello';
Foo.1.id   = 124
Foo.1.name = 'world';

As mentioned in the start of my answer, the index itself does not matter, this code will do exactly the same:

Foo.12345.id   = 123
Foo.12345.name = 'hello';
Foo.54321.id   = 124
Foo.54321.name = 'world';

As long as fields of the same record have the same 'index', CakePHP will understand that they belong 'together'.

When submitting this data and saving it using;

$this->Foo->saveMany($this->data['Foo']); // Just $this->data will probably work as well

CakePHP update two rows via the Foo model;

table 'foos';

id     name
------------------------
123    hello
124    world

Your code seems to use the same 'id' ($qset['Qset']['id']) for each row, which is probably not the right ID to update those records

As we can see at CakePHP Book, the instruction is:

// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);

// **Update**: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);

Considering there are still people looking for this answer in 2014 You must use in the
View: /* (considering the $n counter)*/
$this->input('Question.'.$n.'.order');
$this->input('Question.'.$n.'.id');
Controller: $this->Question->updateAll->($this->request->data['Question']);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!