How to convert a table column data inside eloquent in laravel? - sql

I am trying to convert the 'CHECKTIME' table column datetime to string for using the 'LIKE' operator in sql. The LIKE operator is not support the datetaime data type. So, I have to convert it into string to use LIKE. How can I do it in laravel eloquent? My Code in Controller:
$dailyData=CheckInOutModel::join('USERINFO', 'USERINFO.USERID', '=', 'CHECKINOUT.USERID')
->select('USERINFO.USERID as id','USERINFO.BADGENUMBER as bd', 'USERINFO.NAME as name','USERINFO.Image as photo','CHECKINOUT.*')
->where(CONVERT(VARCHAR(25),' CHECKINOUT.CHECKTIME'),'LIKE',$thisDay.'%')
->orderBy('CHECKINOUT.CHECKTIME','desc')->get();
The SQL Query that work to return the data:
SELECT CHECKINOUT.CHECKTIME
FROM CHECKINOUT
JOIN USERINFO ON USERINFO.USERID=CHECKINOUT.USERID
WHERE CONVERT(VARCHAR(25), CHECKINOUT.CHECKTIME, 126) LIKE '2021-11-23%';

First off, you can use the whereRaw() (see link) method to inject raw SQL in your query.
This would be something like this:
$dailyData=CheckInOutModel::join('USERINFO', 'USERINFO.USERID', '=', 'CHECKINOUT.USERID')
->select('USERINFO.USERID as id','USERINFO.BADGENUMBER as bd', 'USERINFO.NAME as name','USERINFO.Image as photo','CHECKINOUT.*')
->whereRaw('CONVERT(VARCHAR(25), CHECKINOUT.CHECKTIME) LIKE ?', $thisDay.'%')
->orderBy('CHECKINOUT.CHECKTIME','desc')->get();
But since you are working with dates, it's recomended to use dates all the way and not convert the data to compare strings.
Another approach would be to use whereBetween directly with dates. (see link)
Exemple :
$dailyData=CheckInOutModel::join('USERINFO', 'USERINFO.USERID', '=', 'CHECKINOUT.USERID')
->select('USERINFO.USERID as id','USERINFO.BADGENUMBER as bd', 'USERINFO.NAME as name','USERINFO.Image as photo','CHECKINOUT.*')
->whereBetween(
'CHECKINOUT.CHECKTIME',
[
$thisDay,
date('Y-m-d', strtotime('+1 day', $thisDay))
]
)->orderBy('CHECKINOUT.CHECKTIME','desc')->get();
I have over indented the relevent section to make it clear.
Reach out in comments if you have any issue or suggestion to improve it :)

Related

How to convert SQL query to Laravel eloquent

how can I convert my raw sql query to laravel query? I have issues with 'to_date' and tried many things.
This is my code:
select n_reserva,cod_hab_r1,cod_hab_r2,cod_hab_r3,fecha_reserva,fecha_entrada,fecha_salida,tour,dni_r,nombre,apellidos
from reservadas
join huespedes on huespedes.dni=reservadas.dni_r
where fecha_entrada=(select to_date(sysdate) from dual);
My suggest for laravel is this:
DB::table('reservadas')
->select('n_reserva','cod_hab_r1','cod_hab_r2','cod_hab_r3','fecha_reserva',
'fecha_entrada','fecha_salida','tour','dni_r','nombre','apellidos')
->join('huespedes','huespedes.dni','=','reservadas.dni_r')
->where('fecha_entrada','=',function($query){
$query->from('dual')
->select(DB::raw("to_date(sysdate)"));
})
->get();
SQL code works fine, so the problem is in the second one.
I mostly use an online converter to convert my raw SQL query to a query builder for example you can use the below website to convert your code from raw to query builder
https://sql2builder.github.io/
your query
select n_reserva,cod_hab_r1,cod_hab_r2,cod_hab_r3,fecha_reserva,fecha_entrada,fecha_salida,tour,dni_r,nombre,apellidos
from reservadas
join huespedes on huespedes.dni=reservadas.dni_r
where fecha_entrada=(select to_date(sysdate) from dual);
the output
DB::table('reservadas')
->select('n_reserva', 'cod_hab_r1', 'cod_hab_r2', 'cod_hab_r3', 'fecha_reserva', 'fecha_entrada', 'fecha_salida', 'tour', 'dni_r', 'nombre', 'apellidos')
->join('huespedes','huespedes.dni','=','reservadas.dni_r')
->where('fecha_entrada','=',function($query) {
$query->from('dual')
->select(DB::raw("'to_date'(sysdate));
})
->get();

AR/Arel - How can i compose a query to SELECT a conditional CONCAT of columns

I've got a model method that conditionally concatenates the user's username ("login") and real name, if they've saved a real name - otherwise it just shows the username. I'd like to rewrite the query in ActiveRecord or Arel.
It looks like I should use an Arel::Nodes::NamedFunction. But i don't understand how to do the conditional concatenation with a named function. (Does Arel know about "if"? I can't find any reference in the docs.)
def primer_values
connection.select_values(%(
SELECT CONCAT(users.login,
IF(users.name = "", "", CONCAT(" <", users.name, ">")))
FROM users
ORDER BY IF(last_login > CURRENT_TIMESTAMP - INTERVAL 1 MONTH,
last_login, NULL) DESC,
contribution DESC
LIMIT 1000
)).uniq.sort
end
There's also similarly a conditional in ORDER BY.
While generally I abhor Raw SQL in rails given this usage I'd leave it as is. Although I might change it to something a bit more idiomatic like.
User
.order(
Arel.sql("IF(last_login > CURRENT_TIMESTAMP - INTERVAL 1 MONTH,last_login, NULL)").desc,
User.arel_table[:contribution].desc)
.limit(1000)
.pluck(Arel.sql(
'CONCAT(users.login,
IF(users.name = "", "",
CONCAT(" <", users.name, ">")))'))
.uniq.sort
Converting this to Arel without abstracting it into an object of its own will damage the readability significantly.
That being said just to give you an idea; the first part would be 3 NamedFunctions
CONCAT
IF
CONCAT
Arel::Nodes::NamedFuction.new(
"CONCAT",
[User.arel_table[:name],
Arel::Nodes::NamedFuction.new(
"IF",
[User.arel_table[:name].eq(''),
Arel.sql("''"),
Arel::Nodes::NamedFuction.new(
"CONCAT",
[Arel.sql("' <'"),
User.arel_table[:name],
Arel.sql("'>'")]
)]
)]
)
A NamedFunction is a constructor for FUNCTION_NAME(ARG1,ARG2,ARG3) so any SQL that uses this syntax can be created using NamedFunction including empty functions like NOW() or other syntaxes like LATERAL(query).

SSAS Tabular - How to use FORMAT function in DAX summarize function

I have one Date column in my fact table, and due to some client api requirement I need to format this column as string while grouping data using SUMMARIZE function. Below is the sample query, which I am using:
EVALUATE(
CALCULATETABLE(
ADDCOLUMNS(
SUMMARIZE(
'BreakTable',
'BreakTable'[Column1],
'BreakTable'[Column2],
'BreakTable'[DateColumn1], --This needs to be formatted
),
"BreakCount",FORMAT('BreakTable'[BreakCount],"#,##0")
)
))
I have tried using FORMAT function in SUMMARIZE, and that does not work by default. I can not add new column to FactTable, so need to solve this while querying itself.
Is there any other way to achieve this? Any help is appreciated.
As per suggestion, adding more information.
We are using Sql Server 2014.
You could use the SELECTCOLUMNS() function. This function works similarly to the ADDCOLUMNS() function, except that it only returns the columns you specify.
Here is an example of how you can alter your existing query:
EVALUATE(
SELECTCOLUMNS(
SUMMARIZE(
'BreakTable',
'BreakTable'[Column1],
'BreakTable'[Column2],
'BreakTable'[DateColumn1],
),
"Column1", [Column1],
"Column2", [Column2],
"DateColumn1", FORMAT([DateColumn1],"YourFormatHere"), --Format your DateColumn here
"BreakCount",FORMAT('BreakTable'[BreakCount],"#,##0")
)
)
EDIT:
Please note that the SELECTCOLUMNS() function is only available from SQL Server 2016 and up.

Need help converting SQL query to Ruby.

I'm new to Ruby on Rails. I'm trying to determine the proper ruby query for the following SQL query.
Select max(bid_amount) from biddings where listing_id = 1;
I need to extract the maximum value in the bid_amount column. But it has to have a dynamic listing_id.
Try:
Bidding.where('listing_id = :listing_id', listing_id: 1).maximum(:bid_amount)
Update:
To follow up on your comment: since you say you are passing in params[:id], it's best to convert that parameter to integer so that unwanted values don't go to the database. For e.g.
Bidding.where('listing_id = :listing_id', listing_id: params[:id].to_i).maximum(:bid_amount)

Doctrine Query <timestamp

I have a colum "datetime", like this: 2012-06-04 15:40:20.
I want to create a query in Doctrine that I get the data of previous time. Less than 2012-06-04 15:40:20. How can I realize that in Doctrine.
Sorry, I just have no clue.
If I understand your question correctly, I believe the syntax is just:
$datetime = // your timestamp
->where('t.somefield < ?', date('Y-m-d H:i:s', strtotime($datetime))
I am not familiar with Doctrine, but here is standard SQL to do what you want:
select *
from t
where t.datetime in (select max(datetime)
from t
where datetime < '2012-06-04 15:40:20'
)
If Doctrine supports standard SQL syntax, then something like this would work (you might have to input the date/time constant in a different way).