标题看起来有点复杂,但很简单。我有一个带有表和所有东西的Post模型,在PostController中,我将文章传递到视图中,如下所示
在我的控制器中,我从API获取文章,并将其传递给$articles变量,我从数据库中获得我的文章,并将其传递给$posts变量。
public function index()
{
$articles = Http::withHeaders([
'api-key' => config('services.devto.key'),
])->get('http://dev.to/api/articles/me/published');
$articles = json_decode($articles, true);
return view('posts.index', [
'posts' => Post::latest()->filter(request(['search', 'category', 'author']))->paginate(6)->withQueryString(),
'articles' => $articles
]);
}我可以将它们传递到相同的视图中,并按下面的方式执行,这样就可以正常工作了。
<div class="lg:grid lg:grid-cols-3">
@foreach ($posts->skip($posts->onFirstPage() ? 3 : 0) as $post)
<x-postCard :post="$post" />
@endforeach
@foreach ($articles as $article)
<x-articlepostcard :article="$article" />
@endforeach
</div>
这给了我6个帖子,因为我将它们分页,然后在我从API中获得所有10篇文章之后,在第2页中,我又得到了6篇文章,在它们下面,同样的10篇文章再次重复,因为我不能将它们分页,因为它们只是变量中的json。
关于如何使我的观点显示文章和文章的全部分页和按日期排序,有什么想法吗?
发布于 2022-02-24 21:03:18
您可以创建一个数据传输对象来表示一篇文章或一篇文章。
例如(假设您使用的是PHP 8)
class ArticleDTO {
public __construct(
public string $title,
public string $content,
public Carbon $published_at,
)
{
}
}然后,获取文章和文章,并将它们实例化到DTO中,并从中生成一个集合。
$articleCollection = collect();
foreach ($articles as $article) {
$articleCollection->push(
new ArticleDTO(
$article->title,
$article->content,
$article->published_at
)
);
}
// Do the same for the posts然后,可以将按日期排序的集合传递到视图中。
return view('posts.index', [
'articles' => $articleCollection->sortBy('published_at'),
]);对此解决方案的警告
为了保持分页工作,您可能需要手动调用分页器,但是仍然会加载每个请求上的所有数据。
https://stackoverflow.com/questions/71258063
复制相似问题