2016-08-14 85 views
1

我試圖展現在我的主頁2列有2個不同的使用2個不同的SQL查詢

我有一個BrowseController.php文件:

/** 
* @return mixed 
*/ 
public function getTrending() 
{ 
    $posts = $this->posts->getTrending(null, ['category' => Input::get('category'), 'timeframe' => Input::get('timeframe')]); 

    return View::make('post.list')->with('title', t('Trending'))->with('posts', $posts); 
} 

/** 
* @return mixed 
*/ 
public function getLatest() 
{ 
    $posts = $this->posts->getLatest(null, ['category' => Input::get('category'), 'timeframe' => Input::get('timeframe')]); 
    $title = t('Latest'); 

    return View::make('post.list', compact('title', 'posts')); 
} 

而且一個PostsRepository.php文件:

public function getTrending($type = null, $param = []) 
{ 
    isset($param['timeframe']) ? $param['timeframe'] = $param['timeframe'] : $param['timeframe'] = 'month'; 

    $posts = $this->posts($type, $param)->with('comments', 'votes', 'category', 'user', 'votes.user') 
     ->leftJoin('votes', 'posts.id', '=', 'votes.post_id') 
     ->leftJoin('comments', 'posts.id', '=', 'comments.post_id') 
     ->select('posts.*', DB::raw('count(votes.post_id)*5 as popular')) 
     ->groupBy('posts.id')->with('user')->orderBy('popular', 'desc'); 

    $posts = $posts->paginate(perPage()); 

    return $posts; 
} 

public function getLatest($type = null, $param = []) 
{ 
    $posts = $this->posts($type, $param)->with('comments', 'votes', 'category', 'user', 'votes.user')->orderBy('approved_at', 'desc')->paginate(perPage()); 

    return $posts; 
} 

在我的刀片式服務器的PHP文件我試圖使用這2個功能,但只有一個工作,因爲在我的routes.php文件中我有這個:

Route::get('/', ['as' => 'home', 'uses' => '[email protected]']); 

所以@foreach($posts as $post) @endif只加載getLatest但不getTrending

誰能幫助我?

回答

0

您已經告訴您的路線使用getTrending()控制器方法,但getLatest()調用完全以不同的方法存在。如果你想顯示最新的,並在同一頁面趨勢的帖子,將兩者結合起來的方法調用到一個控制器方法:

// BrowseController.php 

public function getLatestAndTrending() 
{ 
    $trendingPosts = $this->posts->getTrending(null, ['category' => Input::get('category'), 'timeframe' => Input::get('timeframe')]); 

    $latestPosts = $this->posts->getLatest(null, ['category' => Input::get('category'), 'timeframe' => Input::get('timeframe')]); 

    return View::make('post.list') 
     ->with('title', t('New and trending')) 
     ->with('trendingPosts', $trendingPosts) 
     ->with('latestPosts', $latestPosts); 
} 

變更路線指向getLatestAndTrending控制器方法:

Route::get('/', ['as' => 'home', 'uses' => '[email protected]']); 

然後在你看來,可以分別迭代趨勢和最新的帖子:

@foreach($trendingPosts as $post) 
    // ... 
@endforeach 

@foreach($latestPosts as $post) 
    // ... 
@endforeach