在 CakePHP 中删除与 PatchEntity 关联的 Table 的记录
Deleting Records From Associated Table With PatchEntity in CakePHP
我有一个 CakePHP 模型,其中一个 Job 有很多 Employees,一个 Employee 属于一个 Job。我用来编辑 Jobs 和 Employees 的视图是 Job 视图。这是来自我的作业控制器的代码:
$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->data 看起来像这样:
'employees' =>[
0 => [
'id' => 1,
... etc ...
当我添加员工时,$this->request->data 有更多数组元素,补丁将新记录添加到员工 table。
当我删除员工时,$this->request->data 的数组元素较少。但补丁不会删除任何记录。 (当数据返回时,我正在用 array_values 修复数组排序)。
当请求中的记录较少时,有没有办法让补丁删除记录?
如果没有,执行删除的最佳方法是什么?
我不知道我是否完全得到你的 question/wanted 结果,但是从你的行
Is there a way I can get the patch to delete records when there are
fewer records in the request?
我读它是因为你想用当前 post 请求中的新关联数据替换 "old" 关联数据。
一个 hasMany 关联默认有 'saveStrategy' => 'append'
(https://api.cakephp.org/3.4/source-class-Cake.ORM.Association.HasMany.html#84-89)。 (我认为是从 3.1 版开始)
您可以将 saveStrategy
更改为 replace
,例如:
$this->hasMany('Employees', [
'className' => 'Employees',
'foreignKey' => 'employee_id',
'saveStrategy' => 'replace'
]);
当saveStrategy
设置为replace
时,只有当前post/patchEntity中的相关数据才会在保存时关联到当前模型记录。现有链接关联数据的外键将设置为空。
我有一个 CakePHP 模型,其中一个 Job 有很多 Employees,一个 Employee 属于一个 Job。我用来编辑 Jobs 和 Employees 的视图是 Job 视图。这是来自我的作业控制器的代码:
$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->data 看起来像这样:
'employees' =>[
0 => [
'id' => 1,
... etc ...
当我添加员工时,$this->request->data 有更多数组元素,补丁将新记录添加到员工 table。
当我删除员工时,$this->request->data 的数组元素较少。但补丁不会删除任何记录。 (当数据返回时,我正在用 array_values 修复数组排序)。
当请求中的记录较少时,有没有办法让补丁删除记录?
如果没有,执行删除的最佳方法是什么?
我不知道我是否完全得到你的 question/wanted 结果,但是从你的行
Is there a way I can get the patch to delete records when there are fewer records in the request?
我读它是因为你想用当前 post 请求中的新关联数据替换 "old" 关联数据。
一个 hasMany 关联默认有 'saveStrategy' => 'append'
(https://api.cakephp.org/3.4/source-class-Cake.ORM.Association.HasMany.html#84-89)。 (我认为是从 3.1 版开始)
您可以将 saveStrategy
更改为 replace
,例如:
$this->hasMany('Employees', [
'className' => 'Employees',
'foreignKey' => 'employee_id',
'saveStrategy' => 'replace'
]);
当saveStrategy
设置为replace
时,只有当前post/patchEntity中的相关数据才会在保存时关联到当前模型记录。现有链接关联数据的外键将设置为空。