1.belongsTo和hasone的用法
在使用模型的ORM的时候出现belongsTo和hasOne都有表示一对一的关系,但是二者并不相同。以下举例说明两者的区别:
首先有user表 字段 id name password字段
然后有user_address表 id user_id city字段
在User模型中关联user_address表的时候使用hasOne,因为在user表中没有关联两个表的外键
在UserAddress模型中关联user表的时候使用belongsTo,因为在user_address表中有关联两个表的外键user_id
也就是外键在谁手中,谁在模型中就写belongsTo
2。如果需要过滤字段怎么办?
如果模型中使用了belongsTo(),是不能再模型中用field过滤的,而是在控制器中,用->with预关联的时候过滤,如图:
$list = $sto->where($where)
->with([
'dianpu' => function ($query) {
$query->withField('id,name');
},
])
但是模型的hasone可以直接用field:
public function profile()
{
return $this->hasOne('Profile'