Get post created date and also post user

I am trying to get the post created date in this format Jun 20, 2020 when i do this {{ post.created_at }} it shows like this Fri Jul 03 2020 23:43:41 GMT+0100 (West Africa Standard Time i want to change it to shit Jun 20, 2020.

And also i have a posts table in my database and i have user_id column which contains the id of the user that make the post, how can i get the username, i tried doing this {{ post.users.username }} and it shows undefined

1 Like

I am providing what I believe could solve your problems based on the assumption that you are using V5.

For the first question, you could fix the issue at model level. Below is what you could do:

import { DateTime } from "luxon";

import {column,BaseModel} from "@ioc:Adonis/Lucid/Orm";

export default class Post extends BaseModel{
  @column.dateTime({
    autoCreate: true,
    serialize: (value?: DateTime) => {
      return value ? value.toLocaleString(DateTime.DATE_MED) : value;
    },
  })
  public createdAt: DateTime;


}

And for your second question, I assume that you already defined relationship between post and user(author) at the model level, something like this:

//App/Models/User.ts

@hasMany(()=>Post)
public posts: HasMany<typeof Post>

//App/Models/Post.ts
@column()
public userId: number //This is supposed to be foreign key on your posts 
                     //table
@belongsTo(()=>User)
public user: BelongsTo<typeof User>

If that’s the case, any time you load a post in your controller, you need to explicitly load the user relationship like this:

const post = await Post.find(postId);
await post.preload('user') 
//you can now pass post object to your view
1 Like