2015-09-11 13 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êトラン・ティアンチュンの答えと、複数のクエリでの結果と同じ効果があります。また、この機能を再利用するかどうかによって異なります。もしそれが一回限りであれば、これを別の場所に置く方がよいでしょう。他の方法はまた、このようなカテゴリのコレクションを返すメソッドを作成するよう、よりダイナミックな可能性があり、あなたは特定の数のためにそれを求めることができます:私は何をしたか

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); 
    }]); 
} 

DBに多くのクエリを行います。このソリューションをする必要があります。 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 $ news) – sanu

関連する問題