从2-3小时开始我就被困在这里了。
我有多到多的关系:
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个结果。
发布于 2015-12-11 20:12:10
根据我对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,ầ,n,Ti,ế,n,Trung的回答具有相同的效果,并导致多个查询。这还取决于您是否要重用此功能。如果是一次性的话,最好把它放在别的地方。其他方法也可以更具动态性,例如创建一个返回类别集合的方法,您可以向它请求一个特定的数目:
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
]);发布于 2015-09-11 14:57:25
我认为,因为您非常渴望加载一个具有多个记录的集合。
要解决这个问题,您需要循环
$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执行许多查询。如果您只想处理一个查询,请签出此Using LIMIT within GROUP BY to get N results per group?
https://stackoverflow.com/questions/32524254
复制相似问题