2015-09-11 19 views
6

Sono rimasto bloccato qui provato da 2-3 ore.laravel 5.1 ottenere correlato 5 notizie di ogni categoria in relazione molti-a-molti

Ho un molti a molti relazione:

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

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

Sto cercando di ottenere le ultime 5 notizie delle relative categorie:

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

La query sopra non funziona per me è che invia un un totale di cinque risultati anziché 5 risultati per ogni categoria.

risposta

1

In base a quello che so su Laravel, potresti provare a farlo in questo modo.

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

Questo ha lo stesso effetto di risposta e si traduce in più query di Le Tran Tiến Trung. Dipende anche dal fatto che stai riutilizzando questa funzionalità o meno. Se è una tantum, potrebbe essere meglio metterlo da qualche altra parte. Altri modi potrebbero anche essere più dinamico, come la creazione di un metodo che restituisce la raccolta di categorie e si può chiedere per un certo numero:

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

Penso, perché fai carico di caricare una raccolta che ha più di un record.

Per risolverlo, è necessario ciclo

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

Questa soluzione farà molte query al DB. Se vuoi fare solo una query, controlla questo Using LIMIT within GROUP BY to get N results per group?

+0

quello che ho fatto è $ front_categories = Categoria :: dove ('in_front ', 1) -> orderBy (' position ',' asc ') -> get(); nella mia categoria modello public function newsTop5() { return $ this-> news() -> orderBy ('created_at', 'desc') -> take (5); } e nella mia lama @foreach ($ front_category-> newsTop5 as $ news) – sanu