2015-09-11 48 views
6

我被困在這裏一直試圖從2-3小時。laravel 5.1獲取相關5多對多關係的每個類別的新聞

我有一個多對多的關係:

class Category extends Model 
{ 
    public function news() 
    { 
     return $this->belongsToMany('App\News'); 
    } 
} 

class News extends Model 
{ 
    public function categories() 
    { 
     return $this->belongsToMany('App\Category'); 
    } 
} 

我想獲得最新的5日消息相關類別:

$front_categories = Category::with(array(
     'news'=>function($query){ 
     $query->where('publish','1')->orderBy('created_at', 'desc')->take(5);})) 
     ->where('in_front', 1)->get(); 

上面的查詢不工作對我來說它給一個每個類別共有5個結果,而不是5個結果。

回答

1

根據我所瞭解的Laravel,你可以嘗試這樣做。

class Category { 

    public function recentNews() 
    { 
     return $this->news()->orderBy('created_by', 'DESC') 
          ->take(5); 
    } 
} 

// Get your categories 
$front_categories = Category::where('in_front', 1)->get(); 

// load the recent news for each category, this will be lazy loaded 
// inside any loop that it's used in. 
foreach ($front_categories as $category) { 
    $category->recentNews; 
} 

這與LêTrầnTiếnTrung的回答具有相同的效果,並導致多個查詢。這還取決於您是否重複使用此功能。如果它是一次性的,最好把它放在別的地方。其它方式也可能是更有活力,如創建一個返回類的集合的方法,你可以要求它的一定數目:

class CategoriesRepository { 

    public static function getFrontCategories(array $opts = []) { 

     $categories = Category::where('in_front', 1)->get(); 

     if (!empty($opts) && isset($opts['withNewsCount'])) 
     { 
      foreach ($categories as $category) 
      { 
       $category->recentNews = static::getRecentNewsForCategory(
        $category->id, 
        $opts['withNewsCount'] 
       ); 
      } 
     } 

     return $categories; 
    } 
} 

$front_categories = CategoriesRepository::getFrontCategories([ 
    'withNewsCount' => 5 
]); 
0

我覺得,因爲你渴望加載一個擁有多條記錄的集合。

爲了解決它,你需要循環

$front_categories = Category::where('in_front', 1)->get(); 

foreach ($front_categories as $fCategory) { 
    $fCategory->load(['news' => function($query) { 
     $query->where('publish','1')->orderBy('created_at', 'desc')->take(5); 
    }]); 
} 

該解決方案將做許多查詢數據庫。如果你只想做1個查詢,結賬Using LIMIT within GROUP BY to get N results per group?

+0

我所做的是 $ front_categories =類別::這裏('in_front ',1) - > orderBy('position','asc') - > get(); 在我的分類模型 public function newsTop5() { return $ this-> news() - > orderBy('created_at','desc') - > take(5); } 和我的刀片 @foreach($ front_category-> newsTop5 as $ news) – sanu