Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Model relation save not working

For hours i have been trying to solve the problem by getting this error: Phalcon\Mvc\Model\Exception: There are no defined relations for the model 'Users' using alias 'adresses'

I have to database-tables USRES & ADRESSES. Its a 1:n relation.

Therefore i have the models below:

Adresses-Model:

class Adresses extends \Phalcon\Mvc\Model {
.....
  public function initialize() {

     public function initialize() {

        $this->belongsTo(
                "user_id", 
                "Users", 
                "id", 
                array(
                    "alias" => "user", 
                    "foreignKey" => true));
    }

}

Users-Model:

class Users extends \Phalcon\Mvc\Model
{
    public function initilize() {

         $this->hasMany(
                 "id", 
                 "Adresses", 
                 "user_id", 
                 array(
                     "alias" => "adresses" ,
                     "foreignKey" => true
                     ) );


    }
}

in Controller:

        $dc_user = new Users();
         $dc_user->email = '[email protected]';

        $dc_adress = new Adresses();
        $dc_adress->prename = "vorname";
        $dc_adress->surname = "nachname";        

        $dc_user->adresses = $dc_adress;

        if($dc_user->save()):
            echo 1;
                else:
            echo 2;
            endif;
        die;

This error is shown on my screen:

Phalcon\Mvc\Model\Exception: There are no defined relations for the model 'Users' using alias 'adresses'
 File=/Users/us/htdocs/_privat/pro/__Projekt-V2/app/controllers/UsersController.php
 Line=140
#0 [internal function]: Phalcon\Mvc\Model->_postSaveRelatedRecords(Object(Phalcon\Db\Adapter\Pdo\Mysql), Array)
#1 /Users/us/htdocs/_privat/pro/__Projekt-V2/app/controllers/UsersController.php(140): Phalcon\Mvc\Model->save()
#2 [internal function]: UsersController->registerAction('1')
#3 [internal function]: Phalcon\Dispatcher->dispatch()
#4 /Users/us/htdocs/_privat/pro/__Projekt-V2/public/index.php(39): Phalcon\Mvc\Application->handle()
#5 {main}


30.8k

Hi,

see in doc, they assign data to the related model using an array syntax.

https://docs.phalconphp.com/en/latest/reference/model-relationships.html#storing-related-records



107.5k
Accepted
answer

It should be initialize not initilize in Users model. Also in Addresses model you have double function.

That did it! unbelievable :-D .... Thanks a alot!

It should be initialize not initilize in Users model. Also in Addresses model you have double function.