cakephp 多个关联到同一模型保存问题

cakephp multiple association to the same model save problems

我有模型交易,分别使用 sender_id 和 recipient_id 外键两次链接到客户

public $belongTo = array(
    'Sender' => array(
        'className' => 'Customer',
        'foreignKey' => 'sender_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Recipient' => array(
        'className' => 'Customer',
        'foreignKey' => 'recipient_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ) 
)

为了保存客户数据,必须放置哪些数据键?这个我试过了。

$data['Transaction']['amount'];
$data['Recipient']['name'];
$data['Sender']['name'];

收件人和发件人别名客户模型。

现在是大问题。收件人和发件人别名是否在保存时解析为客户?

我对 CakePHP 有点生疏,但我相信您的问题的答案是肯定的。

要保存发件人,您需要:

$this->Sender->save();

而不是:

$this->Customer->save();

是的,你的数据格式是正确的。您只需要在事务模型上使用 saveAll 或 saveAssociated。

参见Cookbook for a description of saveAll()。它实际上是一个包装器,它将确定它是否需要执行 saveAssociated()(在您的情况下会这样做)或 saveMany()(将多个记录保存到同一模型)。

$this->Transaction->saveAll($data);

如果您正在对交易模型执行编辑,请务必在表单中包含 Recipient.id 和 Sender.id,它们将被更新而不是创建新记录。