首页 文章

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

提问于
浏览
0

我正在使用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;
});

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

1 回答

  • 2

    嗯这里似乎有点不对劲,

    首先,我可以从 Blog Plugin 看到 Blog <=> Category 它是 MM 关系所以你将 notrainlab_blog_posts 表中找到 category_id ,因为 all relationmaintainedmm-relationrainlab_blog_posts_categories .

    所以我认为你会 select only one category for blog 所以你只能 get related blogs 只有那个类别 . [ assuming from your code and description ]

    我们可以利用这种关系 .

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

    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;
    });
    

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

    如果有任何疑问请评论 .

相关问题