我试图更新/保存可以有多个地址关联的TradingPartner实体(客户和供应商)(TradingPartnerAddresses)。
我有一系列已更改的TradingPartners,我使用Cake的patchEntities()函数将现有记录与修改后的记录合并。
问题是Cake错误地将关联的地址标记为脏,并且当循环通过实体以保存它们时,它试图重新插入现有地址 - 导致重复的地址。
以下代码:
贸易伙伴控制器
//Load the trading partners model
$tradingPartners = TableRegistry::get('TradingPartners');
//find all existing trading partners and their associated addresses
$currentTradingPartners = $tradingPartners->find('all')
->contain(['TradingPartnerAddresses']);
//Patch trading partner changes
//Cake automagically handles 1 level of associations
$patchedTpEntities = $tradingPartners->patchEntities($currentTradingPartners, $partners);
//loop through and save all dirty fields
foreach ($patchedTpEntities as $tpEntity) {
if ($tradingPartners->save($tpEntity)) {
} else {
//TODO
}
}
贸易伙伴表
public function initialize(array $config) {
$this->primaryKey('partner_code');
$this->hasMany('TradingPartnerAddresses', [
'foreignKey' => 'partner_code'
]);
}
贸易伙伴地址表
public function initialize(array $config) {
$this->entityClass('App\Model\Entity\TradingPartnerAddress');
$this->belongsTo('TradingPartners', [
'foreignKey' => 'partner_code'
]);
}
调试($ patchedEtentites);
(int) 0 => object(App\Model\Entity\TradingPartner) {
.....
'trading_partner_addresses' => [],
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'trading_partner_addresses' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'TradingPartners'
任何想法为什么trade_partner_addresses在实际清理时被标记为脏?
答案 0 :(得分:2)
当您使用某些数据修补某个实体时,它会自动标记为脏
$tradingPartners->patchEntities($currentTradingPartners, $partners);
这意味着您正在使用$ partners数据更新$ currentTradingPartners,因此$ currentTradingPartners被修改并标记为脏。
如果你想要原始数据你可以在你的entiy属性上使用getOriginal方法,你也可以用clean方法删除脏标志。
如果你有问题来修补具有关联的实体你必须在patchEntity中传递一系列选项:
$article = $articles->get(1);
$articles->patchEntity($article, $this->request->data(), [
'associated' => ['Tags', 'Comments.Users']
]);