Reputation: 79
So I have an app like twitter but I want to "wall" to have posts from all users but to be filtered by the current user's interests...
I want something like the following:
$posts = PostModel::with('interests')->latest()->get();
$user = UserModel::find(Auth::user()->id);
foreach ($posts as $post) {
foreach($user->interests as $interest){
return only the posts that have the interest_id that matches
the user's interest_ids
}
}
This is my UserModel interests function:
public function interests() {
return $this->belongsToMany('InterestModel', 'users_interests', 'user_id', 'interest_id')->withPivot('interest_id');
}
This is my PostModel interest function:
public function interests() {
return $this->belongsToMany("InterestModel", 'post_interest', 'post_id', 'interest_id');
}
I just can't figure out how I would sort and return the posts?
Thanks
Matt
Upvotes: 0
Views: 165
Reputation: 369
Easy method:
like $user->interests the corresponding $posts->interests is a Collection (http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html).
To check whether a Post has interest $interest, why not check whether it is in this collection: $posts->interests->has($interest);
But in general looping in PHP has bad performance compared to SQL. So why not fetch only the matching posts in the first place?
$userInterests = UserModel::user_interest()->list('id');
$postWithInterest = PostModel::whereHas('post_interest', function($q)
{
$q->whereIn('id', $userInterest);
})->get();
Although above code is untested, i hope it can show the basic idea.
Upvotes: 1