【问题标题】:Insert in tables with hasOne assossiation on cakePHP在cakePHP中插入具有hasOne关联的表
【发布时间】:2018-04-02 08:48:52
【问题描述】:

我正在学习在关联“hasOne”的表中插入记录时遇到问题,当我插入 Table Users 时,它也应该插入 Table Customers 但只是与用户合作。我看过人们有类似的问题,但我真的不知道我做错了什么。感谢您的帮助

我的用户模型

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.');
    }
}

【问题讨论】:

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


    【解决方案1】:

    我虽然你的User 模型不能将user_id 作为它的foreinKey

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 2021-04-17
      • 1970-01-01
      • 2012-07-18
      相关资源
      最近更新 更多