我有四个表的四个雄辩的模型;用户、个人资料、Habs、追随者。我正在尝试检索用户关注者的所有用户帖子和用户帖子。我的桌子看起来像这样;
哈布斯
- ID
- 用户身份
- 住所
- created_at
- 更新时间
用户
- ID
- 用户名
- 电子邮件
- created_at
- 更新时间
简介
- ID
- 用户身份
- 姓名
- 头像
- created_at
- 更新时间
追随者
ID
追随者ID
following_id
created_at
更新时间
我已经在模型中建立了关系。如何使用 Eloquent 选择用户帖子和用户关注的用户帖子。
好吧,我认为您可以从以下内容开始:
class Users extends Eloquent {
protected $table = 'users';
public function profile()
{
return $this->belongsTo('Profile');
}
public function followers()
{
return $this->hasMany('Follower', 'follower_id', 'id');
}
public function following()
{
return $this->hasMany('Follower', 'following_id', 'id');
}
}
class Hab extends Eloquent {
protected $table = 'habs';
public function user()
{
return $this->belongsTo('User');
}
}
class Follower extends Eloquent {
protected $table = 'followers';
}
class Profile extends Eloquent {
protected $table = 'profiles';
}
你应该能够:
正常选择用户
$user = User::find(1);
得到它的住所
$habs = $user->habs;
获得它的追随者
$followers = $user->followers;
获取关注他/她的人
$following = $user->following;
获得他们追随者的所有习惯
foreach($user->followers as $follower)
{
$followerEmail = $follower->email;
$followerName = $follower->profile->name;
$followerHabs = $follower->habs;
}
从他/她关注的人那里获取所有习惯
foreach($user->following as $following)
{
$followingEmail = $following->email;
$followingName = $following->profile->name;
$followingHabs = $following->habs;
}
这是一个很好的用例HasManyThrough。它允许您查询远距离关系。
https://laravel.com/docs/5.5/eloquent-relationships#has-many-through
您只需要在用户模型上设置关系
// Users Model
public function followings()
{
return $this->belongsToMany(
'Users',
'followers', // Assuming this is the table name
'follower_id',
'following_id'
);
}
public function posts()
{
return $this->hasMany('Habs');
}
然后获取用户的帖子
$posts = User::with('posts')->find(1)->posts;
并获得以下用户的帖子
$following_users = User::find(1)->followings()->with('posts')->get();