首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel5.1在多到多的关系中得到每个类别的相关5条新闻

Laravel5.1在多到多的关系中得到每个类别的相关5条新闻
EN

Stack Overflow用户
提问于 2015-09-11 13:06:17
回答 2查看 902关注 0票数 6

从2-3小时开始我就被困在这里了。

我有多到多的关系:

代码语言:javascript
复制
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条新闻:

代码语言:javascript
复制
$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个结果。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-11 20:12:10

根据我对Laravel的了解,你可以试试这样做。

代码语言:javascript
复制
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的回答具有相同的效果,并导致多个查询。这还取决于您是否要重用此功能。如果是一次性的话,最好把它放在别的地方。其他方法也可以更具动态性,例如创建一个返回类别集合的方法,您可以向它请求一个特定的数目:

代码语言:javascript
复制
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
]);
票数 1
EN

Stack Overflow用户

发布于 2015-09-11 14:57:25

我认为,因为您非常渴望加载一个具有多个记录的集合。

要解决这个问题,您需要循环

代码语言:javascript
复制
$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?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32524254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档