2015-09-11 38 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