cakeTp 3.4.9中belongsTo和hasMany之间的关系

时间:2017-07-11 12:29:18

标签: cakephp-3.0

我需要同时保存用户和发票数据。当我提交表单时,用户数据正在保存,但发票表不是。当我打印请求数据时,我得到以下内容:

object(Cake\ORM\Entity) {

'u_firstname' => 'John',
'u_lastname' => 'den',
'u_email' => 'john@man.com',
'u_phone' => '123',
'password' => '123',
'membership_id' => (int) 1,
'Invoices' => [
    'inv_membership_name' => 'basic1',
    'inv_membership_cost' => '55',
    'inv_purchase_date' => '2017-07-11'
],
'id' => (int) 19,
'[new]' => false,
'[accessible]' => [
    '*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Users'

}

我无法保存Invoice部分。我定义了 InvoicesTable.php

 public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('invoices');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);
}

UsersTable是这样的:

$this->hasMany('Invoices', [
        'foreignKey' => 'user_id',
        'joinType' => 'INNER'
    ]);

我使用以下代码保存数据:

$user = $this->Users->newEntity();
if ($this->request->is('post')) {
      $user = $this->Users->patchEntity($user, $this->request->data(), [
            'associated' => [
                'Invoices' 
            ]
        ]);
    if ($this->Users->save($user)) {
       $this->Flash->success(__('The user has been saved.'));
   }else{
       $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
 }

请建议我错过的内容。或者我应该如何调试。

2 个答案:

答案 0 :(得分:0)

当您打印请求数据invoices时,数组应该是这样的:

object(Cake\ORM\Entity) {
   'invoices' => [
        [0] => Array
             (
            ['inv_membership_name'] => 'basic1',
            ['inv_membership_cost'] => '55',
            ['inv_purchase_date'] => '2017-07-11'
        ),
        [1] => array('...') // if you have multiple records
 ],

对于那个更改输入名称在表单中的类似内容:

invoices[]['inv_membership_name']
invoices[]['inv_membership_cost']
invoices[]['inv_purchase_date'] 

请参阅此处Saving HasMany Associations in CakePhp3

答案 1 :(得分:0)

您接近解决方案,但表单中的命名约定有误。正确的名称是invoices.0.inv_membership_name invoices.1.inv_membership_name等我从食谱中包含了相关数据链接的创建输入。

echo $this->Form->control('invoices.0.inv_membership_name');

https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data