在CakePHP上插入带有hasOne assossiation的表

时间:2018-04-02 08:48:53

标签: php database model entity cakephp-3.x

我正在学习在带有关联“hasOne”的表中插入记录时出现问题,当我插入表用户时,它还应插入表客户但仅限于与用户合作。我看起来人们有类似的问题,但我真的不知道我做错了什么。我感谢任何帮助

我的用户模型

class UsersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->addBehavior('Timestamp');

        $this->hasOne('Customers', [
            'foreignKey' => 'user_id'
        ]);
    }

我的客户模式

class CustomersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->addBehavior('Timestamp');

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

我的请求 - > getData()

[
'Users' => [
    'Customers' => [
        'first_name' => 'name',
        'last_name' => 'test',
        'gender' => 'Male',
        'postcode' => '1234'
    ],
    'username' => 'user1',
    'password' => '12134'
],
'done' => '1'
]

我的行动

public function addCustomer()
{
    //Configure::write('debug',true);
    // debug($this->request->getData());

    $usersTable = TableRegistry::get('Users');
    $user = $usersTable->newEntity();
    if ($this->request->is('post')) {
        $user = $usersTable->patchEntity($user,$this->request->getData(),['associated' => ['Customers']]);

        if ($usersTable->save($user)) {

            $this->Flash->success('The Customer has been saved.');
            return $this->redirect(['action' => 'addCustomer']);
        }
        $this->Flash->error('Unable to add the Customer.');
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您的User模型不能user_id作为其foreinKey