Ad

How To List Related Blog Posts In OctoberCMS

- 1 answer

I am building an App with OctoberCMS and wanted to list related blog posts at the bottom of each post page basing on categories. I figured out rainlab_blog_posts table does not have a foreign key pointing to blog categories table. To achieve what wanted I thought of extending the blog_posts table and added category_id as foreign key using a plugin. I defined foreign key constraints in table migration. Everthing seem to be fine. My challenge is, How can I insert category id in posts table each time a new post is created. OctoberCMS create post backend has an option where the author assigns a category to a new blog post by selecting from list. Just don't understand how to pass this category id and insert into rainlab_blog_posts table in category_id field.

This is what I want to achieve in my 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;
});

Or if there is a better way of achieving this will appreciate. Cheers!

Ad

Answer

Hmm seems something wrong here,

As first I can see from Blog Plugin that Blog <=> Category it is MM relation so you will not find category_id in rainlab_blog_posts table as all relation is maintained by this mm-relation table rainlab_blog_posts_categories.

So I think you will select only one category for blog so you can get related blogs for only that category. [ assuming from your code and description ]

we can utilize relationships for that.

So your code can look like this

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

Good thing now you don't need to add that category_id field on rainlab_blog_posts. So, I guess now you Also don't need to worry about adding it during post insertion.

if any doubts please comment.

Ad
source: stackoverflow.com
Ad