简体   繁体   English

如何按当前类别显示相关帖子?

[英]How to show related posts by current category?

In Laravel, posts and categories having many to many relationship. 在Laravel中,帖子和类别具有多对多关系。 That means one post can have multiple categories. 这意味着一个帖子可以有多个类别。 In that case, I want to show related posts by current categories. 在这种情况下,我想按当前类别显示相关帖子。 However I've achieve this by storing current category id in session. 但是,我通过在会话中存储当前类别ID来实现这一点。 But the problem occurs when a post has multiple categories and all are open in different tabs navigated from its respective categories. 但是,当帖子具有多个类别并且所有帖子均在从其相应类别导航的不同选项卡中打开时,就会出现问题。 If I refresh them, related posts are changed to latest category stored in session. 如果我刷新它们,相关的帖子将更改为会话中存储的最新类别。

Please suggest a way to solve this. 请提出解决此问题的方法。 Thank you all in advance. 谢谢大家。 :) :)

$category[] = $request->session()->get('current_category_id');
$relatedPosts = Post::whereHas('category', function($q) use ($category) {
    $q->whereIn('category_id',$category);
})->whereNotIn('id', $currentPost->id)->take(5)->get();

Expected: After refresh, page should show related posts of the category navigated from. 预期:刷新后,页面应显示该类别的相关帖子。

Actual: After refresh, pages are showing related posts of latest category navigated from. 实际:刷新后,页面显示从中导航的最新类别的相关帖子。

For this sort of thing I would normally add 'tags' and tag posts with keywords which then allow display of related posts based on highest number of matching tags (some of your own logic will be required here) 对于这种事情,我通常会添加“标签”和带有关键字的标签帖子,然后根据匹配标签的最大数量显示相关帖子(此处将需要您自己的一些逻辑)

The library I have used in the past is: https://github.com/spatie/laravel-tags 我过去使用的库是: https : //github.com/spatie/laravel-tags

Relying on sessions is difficult, especially since people could end up on your article page directly from a search engine so would have no session history 依赖会话很困难,尤其是因为人们可以直接从搜索引擎进入您的文章页面,因此没有会​​话历史记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM