We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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}


43.9k

Hi,

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

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



145.0k
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.