CakePHP use user_id in model on registration

时间:2016-07-11 20:45:38

标签: registration cakephp-3.x

I am trying to add an Adress and at the same time add/register the user. So the saved adress has the user_id of the user. Saving adress and user always leaves the user_id field in adresses empty.

Maybe I should do it the other way arround? So add all that to the users controller?

The user is not registered at this point by the way.

USERS Table

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

        $this->table('users');
        $this->displayField('id');
        $this->primaryKey('id');
        $this->hasOne('Adresses');        
    }

Adresses Table

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

        $this->table('adresses');
        $this->displayField('name');
        $this->primaryKey('id');
        $this->hasOne('Users', [
            'foreignKey'  => 'user_id'
        ]);      

    }

Add Function in Adresses Controller

public function add() {

$move = $this->Adresses->newEntity();
if ($this->request->is('post')) {
    $adress= $this->Adresses->patchEntity($adress, $this->request->data, [
        'associated' => [
            'Users'
        ]
    ]);

    if ($this->Adresses->save($adress, ['associated' => ['Users']])) {
        $this->Flash->success(__('bla'));

        //return $this->redirect(['controller' => 'pages','action' => 'display','success']);
    } else {
        $this->Flash->error(__('Bla'));
        //return $this->redirect( ['controller' =>'adresses', 'action' => 'display', 'add-fail']);
    }
}
$this->set(compact('adress'));
$this->set('_serialize', ['adress']);

}

0 个答案:

没有答案