通过用户兴趣过滤帖子?

时间:2015-03-18 23:07:31

标签: laravel laravel-4

所以我有一个类似Twitter的应用程序,但我想“挂”来收集所有用户的帖子,但要根据当前用户的兴趣进行过滤...

我想要以下内容:

$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

        }

    }

这是我的UserModel兴趣功能:

  public function interests() {

    return $this->belongsToMany('InterestModel', 'users_interests', 'user_id', 'interest_id')->withPivot('interest_id');
} 

这是我的PostModel兴趣功能:

  public function interests() {

    return $this->belongsToMany("InterestModel", 'post_interest', 'post_id', 'interest_id');

}

我无法弄清楚如何排序并返回帖子?

由于

马特

1 个答案:

答案 0 :(得分:1)

简单的方法:

喜欢$ user->兴趣相应的$ posts->兴趣是一个集合(http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html)。

要检查帖子是否有兴趣$ interest,为什么不检查它是否在此集合中: $ posts-> interests-&的至少一个具有($利息);


但总的来说,与SQL相比,PHP中的循环性能较差。那么为什么不首先只获取匹配的帖子呢?

$userInterests = UserModel::user_interest()->list('id');
$postWithInterest = PostModel::whereHas('post_interest', function($q)
{
    $q->whereIn('id', $userInterest);
})->get();

虽然上面的代码未经测试,但我希望它可以显示基本的想法。

相关问题