Phalcon:1-1关系中的hasOne和belongsTo有什么区别?

Gea*_*any 5 php model relationship phalcon

我有 2 张桌子(2 个型号)

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

Profile
-uid
-name
-age
-phone
-(other fields)
Run Code Online (Sandbox Code Playgroud)

他们有1-1的关系,我实现的关系如下:

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

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

这个实现对吗?我可以用belongsTo替换hasOne吗?谢谢你的帮助!:-)

小智 -1

hasOne 在父模型中定义,belongsTo 在子模型中定义。

一个用户有一个配置文件,并且该配置文件属于一个用户。

您的案例的正确关系定义是:

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

  • 这并没有解释差异,只是说明如何使用它们。 (4认同)