[英]Phalcon: What is the difference between hasOne and belongsTo in 1-1 relationship?
我有 2 張桌子(2 個模型)
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 值,並將它們保存為相關實體。
文檔中沒有太多關於此的內容。 但是,如果您有興趣,可以閱讀 phalcon 源代碼。 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 在父模型中定義,而屬於在子模型中定義。
一個用戶有一個配置文件,該配置文件屬於一個用戶。
您案例的正確關系定義是:
class User extends Model
{
public function initialize()
{
$this->hasOne('uid', 'Profile', 'uid');
}
}
class Profile extends Model
{
public function initialize()
{
$this->belongsTo('uid', 'User', 'uid');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.