doushantun0614 2014-09-23 19:59
浏览 22
已采纳

如何计算没有N + 1问题并加载整个模型的雄辩关系?

I am showing a list of categories, and the article count within each category. I get the expected result, but I am having the N+1 problem.

My CategoriesController index function:

public function index()
{
    return View::make('categories.index', [
        'articleCategories' => Category::where('type', 'articles')->orderBy('name')->get(),
    ]);
}

The Category model has many relationship to articles:

public function articles()
{
    return $this->hasMany('Article');
}

My categories.index view:

@foreach($articleCategories as $articleCategory)
    <p>
    {{ HTML::link(URL::route('articles.category', array('category' => Str::slug($articleCategory->name))), $articleCategory->name) }}
    {{ $articleCategory->articles->count() }}
    </p>
@endforeach

Edit: It works if I eager load all related articles, but since I only need the article count pr category this seems overkill. Will eager loading articles and do ->count() impact performance? Or is this the best way to do it?

  • 写回答

2条回答 默认 最新

  • dri8163 2014-09-23 21:22
    关注
    // helper relation
    public function articlesCount()
    {
        return $this->hasOne('Article')->selectRaw('category_id, count(*) as aggregate')->groupBy('category_id');
    }
    
    // and accessor for fetching it easier
    public function getArticlesCountAttribute()
    {
        if ( ! array_key_exists('articlesCount', $this->relations)) $this->load('articlesCount');
    
        return $this->getRelation('articlesCount')->aggregate;
    }
    

    Then you can do this:

    // eager load in single query
    $categories = Category::with('articlesCount')->get();
    
    // thanks to accessor this will return value and load relation only if needed
    $categories->first()->articlesCount;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用