在CakePHP中从关联表中删除带有PatchEntity的记录 [英] Deleting Records From Associated Table With PatchEntity in CakePHP
问题描述
我有一个CakePHP模型,其中一个作业有很多雇员,而一个雇员属于一个工作.我用于编辑工作和员工的视图是工作视图.这是我的作业控制器中的代码:
I have a CakePHP model where a Job hasmany Employees and an Employee belongsTo a Job. The View I use to edit both Jobs and Employees is a Job view. Here is code from my Job Controller:
$job = $this->Jobs->get($id, [
'contain' => ['Employees']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$req = $this->request->data;
$job = $this->Jobs->patchEntity($job, $req, [
'validate' => false,
'associated' => ['Employees']
]);
$saveResult = $this->Jobs->save($job, [
'validate' => false,
'associated' => ['Employees']
]);
$ this-> request->数据如下:
$this->request->data looks like this:
'employees' =>[
0 => [
'id' => 1,
... etc ...
当我添加员工时,$ this-> request-> data具有更多的数组元素,并且补丁程序将新记录添加到employee表中.
When I add employees, $this->request->data has more array elements and the patch adds the new records to the employees table.
当我删除员工时,$ this-> request-> data的数组元素更少.但是该补丁程序不会删除任何记录. (当数据返回时,我使用array_values修复了数组排序).
When I delete employees, $this->request->data has fewer array elements. But the patch doesn't delete any records. (I am fixing the array ordering with array_values when the data comes back).
当请求中的记录较少时,是否有办法让我删除补丁以删除记录?
Is there a way I can get the patch to delete records when there are fewer records in the request?
如果没有,执行删除的最佳方法是什么?
If not, what's the best way to do the deletes?
推荐答案
我不知道我是否完全理解了您的问题/想要的结果,而是从您的行中获得的
I don't know if I completely get your question/wanted result, but from your line
有没有办法让我获得补丁以删除记录,当有 请求中的记录更少?
Is there a way I can get the patch to delete records when there are fewer records in the request?
在您要在当前发布请求中将旧"的关联数据替换为新的关联数据时,我阅读了它.
i read it as you want to replace the "old" associated data with the new associated data in a current post request.
hasMany关联的默认值为'saveStrategy' => 'append'
(
A hasMany association's has 'saveStrategy' => 'append'
as default (https://api.cakephp.org/3.4/source-class-Cake.ORM.Association.HasMany.html#84-89). (since version 3.1 i think)
您可以将saveStrategy
更改为replace
,例如:
You can change saveStrategy
to replace
like:
$this->hasMany('Employees', [
'className' => 'Employees',
'foreignKey' => 'employee_id',
'saveStrategy' => 'replace'
]);
当saveStrategy
设置为replace
时,保存时仅将当前post/patchEntity中的关联数据关联到当前模型记录.现有链接的关联数据的外键将设置为null.
When saveStrategy
is set to replace
, only associated data in the current post/patchEntity will be associated to the current models record on save. Foreign key of existing linked associated data will be set to null.
这篇关于在CakePHP中从关联表中删除带有PatchEntity的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!