我想创建查询以输出所有属于分页的类别的所有帖子。 我确实很喜欢,但是无论如何在输出中我都有简单的Illuminate \ Database \ Eloquent \ Post集合,没有分页器。 该怎么做?
在我的模特中我有关系 一类有很多帖子。 一个帖子属于一个类别。
public function getItemWithPostsWithSimplePaginator($slug, $perPage = null)
{
$columns = ['id', '_lft', '_rgt', 'parent_id', 'title', 'slug', 'icon', 'description', 'image', 'metatitle', 'metakey', 'metadesc'];
$postcolumns = ['title','slug','category_id','image','fulltext','created_at'];
$result = $this
->startConditions()
->whereSlug($slug)
->select($columns)
->with(['posts' => function($query) use(&$postcolumns, &$perPage) {
$query->select($postcolumns)
->wherePublished(true)
->orderBy('created_at', 'ASC')
->simplePaginate($perPage);
}])
->first();
return $result;
}
如果我做dd,我可以在输出集合中看到11个帖子,尽管$perPage =10
和属于该类别的帖子总数为24。所以它部分起作用。
我唯一想念的是分页器对象。
如果我将simplePaginate
替换为paginate
,则可以看到有10个帖子的收藏集,但是无论如何,没有分页器的普通收藏集。
App\Models\NewsCategory {#838 ▼
+timestamps: false
#guarded: []
#connection: "mysql"
#table: "news_categories"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:12 [▶]
#original: array:12 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"posts" => Illuminate\Database\Eloquent\Collection {#905 ▼
#items: array:11 [▼
0 => App\Models\NewsPost {#925 ▶}
1 => App\Models\NewsPost {#926 ▶}
2 => App\Models\NewsPost {#927 ▶}
3 => App\Models\NewsPost {#928 ▶}
4 => App\Models\NewsPost {#929 ▶}
5 => App\Models\NewsPost {#930 ▶}
6 => App\Models\NewsPost {#931 ▶}
7 => App\Models\NewsPost {#932 ▶}
8 => App\Models\NewsPost {#933 ▶}
9 => App\Models\NewsPost {#934 ▶}
10 => App\Models\NewsPost {#935 ▶}
]
}
]
#touches: []
#hidden: []
#visible: []
#fillable: []
#pending: null
#moved: false
}
答案 0 :(得分:1)
您可以尝试的解决方案之一是使用 setRelation()方法。
$result = $result->setRelation(
'posts',
YourPostModel::select($postcolumns)
->wherePublished(true)
->orderBy('created_at', 'ASC')
->simplePaginate($perPage)
);