0
votes

I have four eloquent models for four tables; Users, Profiles, Habs, Followers. I am trying to retrieve all user posts and posts of users a user follower. My tables looked like this;

Habs

  • id
  • user_id
  • hab
  • created_at
  • updated_at

Users

  • id
  • username
  • email
  • created_at
  • updated_at

Profiles

  • id
  • user_id
  • name
  • avatar
  • created_at
  • updated_at

Followers

  • id

  • follower_id

  • following_id

  • created_at

  • updated_at

    I have set up the relationships in models. How do use the Eloquent to select user posts and posts of users the user follows.

3
Is the Habs table the posts table?SamV

3 Answers

1
votes

Well, I think you can start with something like this:

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

}

And you should be able to:

Select a user normally

$user = User::find(1);

Get its Habs

$habs = $user->habs;

Get its followers

$followers = $user->followers;

Get who are following him/her

$following = $user->following;

Get all habs of their Followers

foreach($user->followers as $follower)
{

    $followerEmail = $follower->email;
    $followerName = $follower->profile->name;
    $followerHabs = $follower->habs;

}

Get all habs from people he/she is following

foreach($user->following as $following)
{

    $followingEmail = $following->email;
    $followingName = $following->profile->name;
    $followingHabs = $following->habs;

}
1
votes

This is a good use case for HasManyThrough. It allows you to query for distant relations.

https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

0
votes

You just need to set relations on Users model only

// 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');
}

Then to get user's posts

$posts = User::with('posts')->find(1)->posts;

And to get posts the following users

$following_users = User::find(1)->followings()->with('posts')->get();