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


Phalcon: What is the difference between hasOne and belongsTo in 1-1 relationship?

我有两个表(两个模型(

User
-uid
-email
-password
-(other fields)
Profile
-uid
-name
-age
-phone
-(other fields)

他们有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');
    }
}

这个实施是对的?我可以用belongsTo代替hasOne吗?谢谢你的帮助!:-(

好吧,已经有一段时间了,但我也在质疑同样的事情。总的来说,他们看起来定义了相同的关系,但事实并非如此,而且存在一些行为差异。

正如另一个答案中所提到的,正确的关系应该是:

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

例如,在处理相关实体时,phalcon模型处理相关实体的id分配。以下代码段在关系设置正确的情况下有效:

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

在这种情况下,您不需要指定uid值,并将它们保存为相关实体。

文档中没有太多关于这方面的内容。但如果你感兴趣,你可以阅读阴茎的来源。https://github.com/phalcon/cphalcon/blob/master/phalcon/Mvc/Model.zep

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');
    }
}

使用hasOne((可以获取用户的地址。

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

使用belongsTo((,如果您有用户的地址,就可以获取该用户。

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

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');
    }
}