检索用户帖子和朋友帖子


Retrieve user posts and friends post

我有四个表的雄辩模型;用户、个人资料、哈布斯、追随者。我正在尝试检索所有用户帖子和用户关注者的帖子。我的桌子看起来像这样;

哈布斯

  • 编号
  • user_id
  • 有害藻华
  • created_at
  • updated_at

用户

  • 编号
  • 用户名
  • 电子邮件
  • created_at
  • updated_at

配置 文件

  • 编号
  • user_id
  • 名字
  • 化身
  • created_at
  • updated_at

追随 者

  • 编号

  • follower_id

  • following_id

  • created_at

  • updated_at

    我已经在模型中设置了关系。如何使用雄辩来选择用户帖子和用户关注的用户帖子。

好吧,我认为你可以从这样的事情开始:

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;
}

从他/她关注的人那里获得所有 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();