任何机构都可以告诉我
之间的主要区别是什么BelongsTo 和 HasOne 在 eloquent 中的关系.
Can any body tell me what is the main difference between
the BelongsTo and HasOne relationship in eloquent.
BelongsTo 是 HasOne 的逆.
BelongsTo is a inverse of HasOne.
我们可以使用belongsTo 方法定义hasOne 关系的逆.以 User 和 Phone 模型为例.
We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with
UserandPhonemodels.
我给出了从用户到电话的 hasOne 关系.
I'm giving hasOne relation from User to Phone.
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('AppPhone');
}
}
使用这种关系,我可以使用 User 模型获取 Phone 模型数据.
Using this relation, I'm able to get Phone model data using User model.
但是使用 HasOne 的逆过程是不可能的.就像使用电话模型访问用户模型一样.
But it is not possible with Inverse process using HasOne. Like Access User model using Phone model.
如果我想使用Phone访问User模型,则需要在Phone模型中添加BelongsTo.
If I want to access User model using Phone, then it is necessary to add BelongsTo in Phone model.
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('AppUser');
}
}
您可以参考此链接了解更多详情.
You can refer this link for more detail.
这篇关于Laravel 中的 BelongsTo 和 HasOne 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
MySQLi准备好的语句&foreach 循环MySQLi prepared statement amp; foreach loop(MySQLi准备好的语句amp;foreach 循环)
mysqli_insert_id() 是从整个服务器还是从同一用户获Is mysqli_insert_id() gets record from whole server or from same user?(mysqli_insert_id() 是从整个服务器还是从同一用户获取记录?)
PHP MySQLi 无法识别登录信息PHP MySQLi doesn#39;t recognize login info(PHP MySQLi 无法识别登录信息)
mysqli_select_db() 需要 2 个参数mysqli_select_db() expects exactly 2 parameters(mysqli_select_db() 需要 2 个参数)
Php mysql pdo 查询:用查询结果填充变量Php mysql pdo query: fill up variable with query result(Php mysql pdo 查询:用查询结果填充变量)
MySQLI 28000/1045 用户“root"@“localhost"的访问MySQLI 28000/1045 Access denied for user #39;root#39;@#39;localhost#39;(MySQLI 28000/1045 用户“root@“localhost的访问被拒绝)