2015-03-18 143 views
0

所以我有一个像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

简单的方法:

像$用户>感兴趣相应的$ posts->的利益是一个集合(http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html)。

要检查邮政是否有利息$利息,为什么不检查它是否在这个集合中: $ posts-> interests-> has($ interest);


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

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

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