【问题标题】:Laravel Eloquent: Order results by eaged loaded model.property, and paginate the resultLaravel Eloquent:按预先加载的 model.property 排序结果,并对结果进行分页
【发布时间】:2017-07-31 14:01:21
【问题描述】:

假设我有三个模型:PostCategoryTag

帖子belongsTo 类别和类别hasMany 帖子。

manyToManyTagCategory 之间存在关系。

我想按类别名称列出我的帖子并对结果进行分页。

Post::with('category','category.tags')
  ->orderBy('category.name') //this is the bogus line
  ->paginate(10);

但是这种语法不起作用。


我尝试的是this as:

Post::select('categories.*')
  ->join('categories','posts.category_id','=','categories.id')
  ->orderBy('categories.name)
  ->paginate(10);

但随后我丢失了急切加载的数据。

如果我删除select() 子句,那么我会得到垃圾数据,因为categories.id 会覆盖posts.id。见here


有什么优雅的方法可以解决这个问题吗? 在这上面花了几个小时后,我离迭代分页帖子和“手动”加载关系只有一步之遥:

foreach($posts as $post) {
  $post->load('category','category.tags');
}

甚至不确定这是否有缺点,但它似乎不正确。如果我错了,请纠正我。

最后一步的更新:急切加载分页结果将不起作用,所以如果我走那条路,我需要实施更丑陋的修复。

【问题讨论】:

  • 你试过Post::with('category','category.tags')->select('categories.*') ->join('categories','posts.category_id','=','categories.id') ->orderBy('categories.name) ->paginate(10); ??
  • 是的,只要我添加select()with() 方法中指定的任何数据都不会返回。我确实得到了category,但它是一个空数组。
  • with 不起作用,因为select('categories.*') 是错误的,你需要posts 表字段来代替。查看我的答案(现已更新)

标签: laravel pagination eloquent eager-loading


【解决方案1】:

您应该可以同时使用joinwith

Post::select('posts.*') // select the posts table fields here, not categories
->with('category','category.tags')
->join('categories','posts.category_id','=','categories.id')
->orderBy('categories.name)
->paginate(10);

请记住,with 子句不会改变您的查询。只有在查询执行后,才会收集n+1个关系。

您的解决方法确实失去了急切加载的好处。但是您也可以在集合/分页器(查询结果)上调用load(..),因此调用->paginate(10)->load('category','category.tags') 等效于上面的查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多