我与其他 6 张桌子有这样的关联
company ==> hasMany Cohorts
和 Cohorts ==> contains hasMany
例如:CohortTimeConfig
。
现在我正在从群组表中检索默认值,这样就可以了。
$cohorts = $this->Companies->Cohorts
->find('all', [
'conditions' => [
'company_id IS NULL and status_id = 1'
],
'contain' => [
'CohortConfigs',
'CohortPpmCategories',
'CohortRanges',
'CohortRoadClassConfig',
'CohortTimeConfig',
'CohortWeatherConfig'
],
'order' => ['id' => 'ASC']
])
->toArray();
现在我正在做的就是像这样改变$cohorts
$company_id = $company->id;
array_walk($cohorts, function (&$cohort, $index) use ($company_id) {
unset($cohort['id']);
$cohort['company_id'] = $company_id;
//cohort_time_config
if(!empty($cohort['cohort_time_config'])){
array_walk($cohort['cohort_time_config'], function (&$cohort_time_config, $key) {
unset($cohort_time_config['id']);
unset($cohort_time_config['cohort_id']);
});
}
});
最后我试图像这样保存所有具有关联的值
$allCohorts = $this->Companies->Cohorts->newEntity();
$allCohorts = $this->Companies->Cohorts->patchEntity($allCohorts, $cohorts);
debug(
$this->Companies->Cohorts->save($allCohorts,[
'atomic'=>true,
'validate' => true,
'associated' => [
'CohortConfigs',
'CohortPpmCategories',
'CohortRanges',
'CohortRoadClassConfig',
'CohortTimeConfig',
'CohortWeatherConfig'
]
])
);
我想提一下,我的
//debug($allCohorts->errors());
没有给出任何错误。这意味着所有规则检查都正常。但数据没有被保存。
有人可以帮助我吗?我该如何调试它为什么不保存数据?
您的查询看起来像检索许多数据并想要保存许多数据,但您使用就像保存一个数据
您的实体
$allCohorts = $this->Companies->Cohorts->newEntity();
$allCohorts = $this->Companies->Cohorts->patchEntity($allCohorts, $cohorts);
应该是这样的
$allCohorts = $this->Companies->Cohorts->newEntities();
$allCohorts = $this->Companies->Cohorts->patchEntities($allCohorts, $cohorts);
或者您也可以使用
$allCohorts = $this->Companies->Cohorts->newEntities($allCohorts);
$this->Companies->Cohorts->saveMany($allCohorts);
有关更多信息,请参阅保存多个实体