I have some tables like these:
users
, followers_pivot
, activities
In my User
model, all relations are set and working correctly.
Some methods from my User.php model:
class User extends Eloquent {
//The ones I follow
public function imFollowing() {
return $this->belongsToMany('User', 'followers_pivot', 'follower_id', 'followee_id');
}
//The people who's following me
public function followers() {
return $this->belongsToMany('User', 'followers_pivot', 'followee_id', 'follower_id');
}
//shows all activities of the user
public function activities() {
return $this->hasMany('Activity', 'userID');
}
}
I want to fetch activities of everyone I'm following.
I can fetch this way:
User::with('imFollowing.activities')->find(11);
But, it's not enough. They are under imFollowing
collection, and separated by each user.
I want to fetch activities directly and not separated under imFollowing
s.
I thought of a Has-Many-Through relationship, but I couldn't put it together.
This is what I've tried using hasManyThrough
:
//User.php Model
public function activityFeed() {
return $this->hasManyThrough('Activity', 'User', 'id', 'userID');
}
And
//in a route
return User::with('activityFeed')->find(11);
But this returns the collection null
.
Edit: I can do this using Fluent way:
Activity::join('users', 'activities.userID', '=', 'users.id', 'inner')
->join('followers_pivot', 'followers_pivot.followee_id', '=', 'users.id', 'inner')
->where('followers_pivot.follower_id', 11)
->orderBy('activities.id', 'desc')
->select('activities.*')
->get();
How can I achieve this using Eloquent? This will be only place where I'll be using Fluent, and I'm not quite satisfied with it. Is the polymorphic approach better for this? If so, how?
Thanks in advance,