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.
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