如何在OctoberCMS中列出相关的博客文章

时间:2018-04-11 17:56:59

标签: laravel octobercms

我正在使用OctoberCMS构建应用程序,并希望根据类别列出每个帖子页面底部的相关博客帖子。我想通了rainlab_blog_posts表没有指向博客类别表的外键。为了达到想要的目的,我想扩展blog_posts表并使用插件将category_id添加为外键。我在表迁移中定义了外键约束。 Everthing似乎很好。我的挑战是,每次创建新帖子时,如何在posts表中插入类别ID。 OctoberCMS创建帖子后端有一个选项,作者通过从列表中选择为新博客帖子分配类别。只是不明白如何传递此类别ID并插入category_id字段中的rainlab_blog_posts表。

这是我想要在我的API中实现的目标:

routes.php文件

use Rainlab\Blog\Models\Post;
Route::get('apiv1/related-posts/{postid}',function($id)
{
$post = Post::where('id',$id)->first();

$posts = Post::where('category_id',$post->category_id)
->where('id','!=',$id)
->orderBy('views','desc')
->get()->take(5);
return $posts;
});

或者,如果有更好的方法实现这一点,将会欣赏。干杯!

2 个答案:

答案 0 :(得分:2)

嗯这里似乎有点不对劲,

首先,我可以从Blog Plugin看到Blog <=> Category MM 关系,因此您会在category_id中找到rainlab_blog_postsall relationmm-relation <{}}表格rainlab_blog_posts_categories 维护

所以我认为你会select only one category for blog所以你可以get related blogs仅针对那个类别。 [根据您的代码和说明假设]

  

我们可以利用关系

所以你的代码看起来像这样

use Rainlab\Blog\Models\Post;

Route::get('apiv1/related-posts/{postid}', function($id)
{
    $post = Post::where('id',$id)->first();

    // we need this because there will be mm relation so
    // we fetch first category and this will be based on 
    // [ name sorting - does not matter as there will be only one cat. ]
    $firstCategory = $post->categories()->first();

    // now we fetch only that post which are related to that category
    // but we skip current post and sort them and pick 5 posts
    $posts = $firstCategory->posts()
        ->where('id', '!=', $id)
        ->orderBy('views','desc')
        ->limit(5) // use limit instead of take()
        ->get(); 

    // use limit instead of take() as we don't need extra data so 
    // just put limit in sql rather fetching it from db then 
    // putting limit by code - limit() is more optimised way

    return $posts;
});
  

现在好了,你不需要在category_id上添加rainlab_blog_posts字段。 所以,我猜你现在也不用担心在插入后添加它。

如有疑问请发表评论。

答案 1 :(得分:1)

如果您只想显示相关博客文章而不必自定义博客数据库,则有一个名为Related Articles的OctoberCMS插件 需要rainlab博客插件。它将显示属于该帖子类别的所有其他文章。

  1. 在“后端”菜单上,依次转到“设置”,“系统”和“更新和插件”。
  2. 转到安装插件。搜索插件相关文章。创建者是 Tallpro 。安装它。
  3. 转到CMS。在需要相关文章的页面上,转到组件并拖动“相关文章”。保存并预览。您还可以派生该组件以编辑您希望相关文章的显示方式。您将在文档中找到更多信息。

    如果您遇到任何问题,请随时咨询,也可以查看插件评论中遇到的问题及其解决方案。
相关问题