5

I have 2 tables (2 models)

User
-uid
-email
-password
-(other fields)

Profile
-uid
-name
-age
-phone
-(other fields)

They have 1-1 relationship and I implemented the relationship as following:

class User extends Model
{
    public function initialize()
    {
        $this->hasOne('uid', 'Profile', 'uid');
    }
}

class Profile extends Model
{
    public function initialize()
    {
        $this->hasOne('uid', 'User', 'uid');
    }
}

This implementation is right? Can I replace hasOne by belongsTo? Thank you for help! :-)

Phantom
  • 1,704
  • 4
  • 17
  • 32
Kevin
  • 1,403
  • 4
  • 18
  • 34
  • 2
    I think this Ruby answer is correct for Phalcon too: http://stackoverflow.com/questions/3808926/whats-the-difference-between-belongs-to-and-has-one – Phantom Jul 13 '14 at 06:28

3 Answers3

3

Well, it's been a while, but i was questioning the same thing. Overall, they look like they define the same relation but they don't and there are some behavior differences.

As mentioned in another answer, the correct relationship should be :

class User extends Model
{
    public function initialize()
    {
        $this->hasOne('uid', 'Profile', 'uid');
    }
}
class Profile extends Model
{
    public function initialize()
    {
        $this->belongsTo('uid', 'User', 'uid');
    }
}

When working with related entities for example, phalcon models handle id assignment of related entity. The following snippet works if and only if the relations are set correctly :

$user = new User();
$user->profile = new Profile();
$user->save();

In this case, you don't need to specify the uid value, and save them as related entities.

There aren't much about this in documentation. But if you're interested, you can read the phalcon source. https://github.com/phalcon/cphalcon/blob/master/phalcon/Mvc/Model.zep

1
class User extends Model
{
    // Get the phone record associated with the user.
    public function address()
    {
        return $this->hasOne('id', 'App\Address', 'id');
    }
}
...

class Address extends Model
{
    // Get the user lives here.
    public function user()
    {
        return $this->belongsTo('id', 'App\User', 'id');
    }
}

With hasOne() you can get user's address.

$address = User::find(1)->address;

And with belongsTo() you can get the user if you have its address.

$user = Address::find(1)->user;
-1

hasOne is defined in the parent model while belongsTo is defined in the child model.

A User hasOne Profile and that Profile belongsTo one User.

The correct relationship definitions for your case would be:

class User extends Model
{
    public function initialize()
    {
        $this->hasOne('uid', 'Profile', 'uid');
    }
}
class Profile extends Model
{
    public function initialize()
    {
        $this->belongsTo('uid', 'User', 'uid');
    }
}