2015-03-18 76 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(); 

雖然上面的代碼是未經測試的,但我希望它能夠顯示出基本的想法。