I'm trying to save an Order entity, but patchEntity always set two fields that are foreign keys to null.
Orders are associated to Addresses with 2 associations (Delivery and Invoice).
Associated addresses already exists, so I just want to save address id as a foreign key into Orders table.
OrdersTable
namespace OrderManager\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use OrderManager\Model\Entity\Order;
/**
* Orders Model
*/
class OrdersTable extends Table {
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config) {
$this->table('orders');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Contacts', [
'foreignKey' => 'contact_id',
'joinType' => 'INNER',
'className' => 'ContactManager.Contacts'
]);
// ...
$this->belongsTo('DeliveryAddresses', [
'foreignKey' => 'delivery_address',
'className' => 'ContactManager.Addresses'
]);
$this->belongsTo('InvoiceAddresses', [
'foreignKey' => 'invoice_address',
'className' => 'ContactManager.Addresses'
]);
}
public function validationDefault(Validator $validator) {
// ...
$validator
->add('delivery_address', 'valid', ['rule' => 'numeric'])
->allowEmpty('delivery_address');
$validator
->add('invoice_address', 'valid', ['rule' => 'numeric'])
->allowEmpty('invoice_address');
// ...
}
Controller
$data = [
// ...
'contact_id' => 34,
'delivery_address' => 8,
'invoice_address' => 8,
'currency' => 'Euro',
'total_paid' => '100.00',
'shipping_number' => ''
// ...
];
$entity = $this->Orders->newEntity();
$entity = $this->Orders->patchEntity($entity, $data);
debug($entity);
debug($entity) always tells me :
'delivery_address' => null,
'invoice_address' => null,
When I remove the belongsTo associations (DeliveryAddresses and InvoiceAddresses), my fields get the numeric value (8). But I need these associations.
How can I keep these associations and save numeric values for the foreign keys ?
答案 0 :(得分:3)
外键名称与关联属性名称(存储关联数据的位置)冲突,默认情况下是从关联名称派生的,如果是belongsTo
,则为#&# 39; s关联名称的单数下划线变体,即delivery_address
和invoice_address
。
参见 Cookbook > Database Access & ORM > Associations > BelongsTo Associations
要解决此问题,请遵守约定并将_id
附加到外键,即delivery_address_id
和invoice_address_id
,或使用propertyName
选项更改属性名称
$this->belongsTo('DeliveryAddresses', [
'propertyName' => 'delivery_address_data',
//...
]);
$this->belongsTo('InvoiceAddresses', [
'propertyName' => 'invoice_address_data',
//...
]);
除非您使用旧版数据库,否则我强烈建议您选择以前的解决方案,并使您的外键符合约定!