我有一个 Laravel 项目并使用:
User.php 作为模型
public function posts() {
return $this->hasMany(Post::class, 'user_id');
}
public function feedPosts() {
return $this->hasManyThrough(Post::Class, Follow::Class, 'user_id', 'user_id', 'id', 'followeduser');
}
UserController.php 作为控制器
public function showCorrectHomepage(User $username) {
$this->getSharedData($username);
return view('homepage-feed', ['posts' => auth()->user()->feedPosts()->latest()->paginate(10)]);
}
homepage-feed.blade.php 作为视图
@foreach($posts as $post)
<a href="/post/{{$post->id}}" class="list-group-item list-group-item-action">
<img class="avatar-tiny" src="{{$post->findUser->avatar}}" />
<strong>{{$post->title}}</strong>
<span class="text-muted small">
vom {{$post->created_at->format('d.m.Y')}} geschrieben um {{$post->created_at->format('H:i')}} Uhr
</span>
</a>
@endforeach
一切都很好。
User.php 模型中的“feedPosts”函数返回用户已订阅的帖子。
User.php 模型中的“posts”函数返回用户撰写的帖子。
目前,用户订阅的帖子显示在主页提要视图中。
目标是显示用户已订阅并自己撰写的帖子。
我还没有设法合并这两个查询。不过,我也是 Laravel 初学者。
我已经尝试过了
public function showCorrectHomepage(User $username) {
$this->getSharedData($username);
$usersposts = auth()->user()->posts()->latest()->get();
$usersabos = auth()->user()->feedPosts()->latest()->get();
$allposts = $userposts->union($userabos)->paginate(10);
return view('homepage-feed', ['posts' => $allposts);
}
但总有一些我不明白的错误。
如有任何帮助,我将不胜感激。非常感谢! 最好的问候丹尼斯
有两种方法可以解决这些问题。决定您需要哪一个。希望您能得到想要的解决方案
使用unionAll和手动分页
公共函数showCorrectHomepage(用户$用户名){ $this->getSharedData($用户名);
$userPosts = auth()->user()->posts()->latest();
$feedPosts = auth()->user()->feedPosts()->latest();
// Combine the queries using unionAll
$allPosts = $userPosts->unionAll($feedPosts)->get();
// Manually paginate the combined results
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 10;
$currentPageResults = $allPosts->slice(($currentPage - 1) * $perPage, $perPage)->all();
$paginatedPosts = new LengthAwarePaginator($currentPageResults, $allPosts->count(), $perPage);
return view('homepage-feed', ['posts' => $paginatedPosts]);
}
使用 Eloquent 集合和分页
公共函数showCorrectHomepage(用户$用户名){ $this->getSharedData($用户名);
// Get the posts written by the user
$userPosts = auth()->user()->posts()->latest()->get();
// Get the posts from the users the user follows
$feedPosts = auth()->user()->feedPosts()->latest()->get();
// Merge the two collections
$allPosts = $userPosts->merge($feedPosts)->sortByDesc('created_at');
// Paginate the combined collection
$paginatedPosts = new LengthAwarePaginator(
$allPosts->forPage(LengthAwarePaginator::resolveCurrentPage(), 10),
$allPosts->count(),
10
);
return view('homepage-feed', ['posts' => $paginatedPosts]);
}