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 relations

hi all, I'm new to Phalcon and trying to understand the model relations.

I have a very simple hasOne() relationship.

    $test1 = Models::getModel('Test1');
    $test1->name = 'test1 name';
    //$test1->test2_id // I have this on the model which I would expect to be populated by child->id

    $test2 = Models::getModel('Test2');
    $test2->name = 'Test2';

    $test1->test2 = $test2; // I believe this is a magic param.

    $test1->save()

    So, it does save both records, but Test1->test2_id is 0, where I would expect it to be test2->id

    More setup info:

    Test1 model
        public function initialize()
        {
            $this->hasOne("test2_id", "Test2", "id");
        }

    Test2 model
        public function initialize()
        {
            $this->hasOne("id", "Test1", "test2_id");
        }

    Any ideas ? a little confused...


1.3k
Accepted
answer

Think I figured it out, I changed the

Test1 model
    public function initialize()
    {
        $this->hasOne("test2_id", "Test2", "id");
    }

to

Test1 model
    public function initialize()
    {
        $this->BelongsTo("test2_id", "Test2", "id");
    }

and it works.

hasOne is actually for define access to model from which we are creating relation like for example we have:

user
id
profileId
profile
id
firstName
lastName

And then with relations

class User
{
    public function initialize()
    {
        $this->belgonsTo('profileId','Profile','id',['alias'=>'profile']);
    }
}
class Profile
{
    public function initialize()
    {
        $this->hasOne('id','User','profileId',['alias'=>'user']);
    }
}

Using $user->profile will give us profile, using $profile->user will give us user.