Transient fields in Lucid


#1

Is there a way to achieve the hibernate @Transient type in Lucid Models.

I want to split the ‘created_at’ datetime into two fields ‘date’ and ‘time’, but i dont want to save ‘date’ and ‘time’ to table.

need to generate date and time at querying the data, similar like the existing “static castDates” type.


#2

Why not only use DATE() function and the TIME() function both available in MySQL Server

So You have stored a record like this

2019-02-05 23:50:00

This is only one record but I wanna get it split into 2 separated values

In pure SQL you can do this


SELECT DATE(fecha) AS Date FROM demo;

SELECT TIME(fecha) AS Time FROM demo;

Result


Date
2019-02-05

Time
23:50:00

In Lucid you can do this


const datos = await User.query()
.select(Database.raw('DATE_FORMAT(created_at, "%Y-%m-%d") AS Date'))
.fetch()

To get this

{ "Date": "2019-01-23" },

And do this


const datos = await User.query()
				.select(Database.raw('TIME(created_at) AS Time'))
				.fetch()

To get this

{ "Time": "21:46:34" },


#3

Hi @ShadowPaz,

Thanks for the idea, but i cannot do two separate queries for date and time.
I want to do it will regular Lucid fetch().

For ex:

User.all() or User.query().fetch() will return

{
id:1,
created_at: ‘2019-02-05 23:50:00’,
name:‘admin’
}

now with the same query i want the result to be

{
id:1,
created_at: ‘2019-02-05 23:50:00’,
date : ‘2019-02-05’,
time: ‘23:50:00’,
name:‘admin’
}

I am trying to do the same with edgejs template also, with no success as of now
This date separation is mostly used in displaying the UI FrontEnd(in edge).

Thanks,
Sujai.K


#4

You can create a date and time fields in DB and then play with setters.


#5

but he says, he doesnt want two fields


#6

hi @ShadowPaz & @physio… thanks for the input.
I solved this issue by addind globals in edge.

Adding the below code in hooks.after.providersBooted

const timeformat = “HH:mm”;
const dateformat = “YYYY-MM-DD”;

const View = use(‘View’)
View.global(‘time’, (dateTime) => {
return moment(dateTime).format(timeformat)
})

View.global(‘date’, (dateTime) => {
return moment(dateTime).format(dateformat)
})

and calling from .edge file as

{{date(data.updated_at)}} and {{time(data.updated_at)}}