nathan
nathan

Reputation: 163

Get posts from following Laravel Eloquent

I am building a social network where the user will have a stream like Twitter of all the posts from the people that they follow.

What is the best way to query this with Laravel Eloquent?

I have 3 tables

users

id | username | etc...|

relationships

id | user_id |follows_id |

posts

id | user_id | post|

Upvotes: 0

Views: 125

Answers (1)

The Alpha
The Alpha

Reputation: 146191

You may try something like this (Basic Idea):

users

id | username | etc...

posts

id | user_id | post_content

favorites (relationships)

id | user_id |post_id

Define the Post class something like this:

class Post extends Eloquent {

    //...

    public function favorites()
    {
        return $this->hasMany('Favorite');
    }

}

Define the favorite class:

class Favorite extends Eloquent {
    // ...
}

Query for the posts:

$posts = Post::whereHas('favorites', function($q) {
    $q->where('user_id', Auth::user()->id);
})->get();

Upvotes: 0

Related Questions