我的数据库中有 3 个表:
users (id);
interests (id);
users_interests (user_id, interests_id);
我希望能够以这种方式获取所有用户的兴趣:
$interests = $user->interests
这是我在 User.php 模型中写的内容,遵循 laravel 的文档:
public function interests() {
return $this->hasManyThrough(
'App\Interest', 'App\UserInterest',
'user_id', 'id', 'interest_id'
);
}
但即使用户有游戏,它也会返回空。所以一定是我做错了什么
任何人都可以帮助我吗?
我认为 abelongs to many
可以完成这项工作:
public function interests() {
return $this->belongsToMany(
'App\Interest',
'users_interests',
'user_id',
'interests_id'
);
}
与文档中的示例非常相似
如果您要将users_interests
表重命名为单数形式interest_user
并将列重命名interests_id
为单数形式,则只需要第一个参数:
public function interests() {
return $this->belongsToMany(App\Interest::class);
}
根据我的理解,hasManyThrough
用于在关系中向前跳转(也在文档中描述):
“has-many-through”关系为通过中间关系访问远距离关系提供了便捷的捷径。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句