jed*_*ylo 40
主要区别在于关系的哪一方持有关系的外键.调用$ this-> belongsTo()的模型是一对一和多对一关系中拥有的模型,并且拥有拥有模型的密钥.
示例一对一关系:
class User extends Model {
public function car() {
// user has at maximum one car,
// so $user->car will return a single model
return $this->hasOne('Car');
}
}
class Car extends Model {
public function owner() {
// cars table has owner_id field that stores id of related user model
return $this->belongsTo('User');
}
}
Run Code Online (Sandbox Code Playgroud)
示例一对多关系:
class User extends Model {
public function phoneNumbers() {
// user can have multiple phone numbers,
// so $user->phoneNumbers will return a collection of models
return $this->hasMany('PhoneNumber');
}
}
class PhoneNumber extends Model {
public function owner() {
// phone_numbers table has owner_id field that stores id of related user model
return $this->belongsTo('User');
}
}
Run Code Online (Sandbox Code Playgroud)
Ket*_*iya 11
BelongsTo是HasOne的反转.
我们可以使用belongsTo方法定义hasOne关系的逆.举个简单的例子
User和Phone模型.
我从用户到手机给予了一个关系.
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
Run Code Online (Sandbox Code Playgroud)
使用这种关系,我可以使用用户模型获取Phone模型数据.
但使用HasOne的逆过程是不可能的.喜欢使用手机型号的Access User模型.
如果我想使用手机访问用户模型,则必须在手机型号中添加BelongsTo.
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
Run Code Online (Sandbox Code Playgroud)
您可以参考此链接以获取更多详细信息.
| 归档时间: |
|
| 查看次数: |
12225 次 |
| 最近记录: |