Use SQL query in Laravel - sql

this is my sql Query:
SELECT DISTINCT batch_job_instance.JOB_NAME, MAX(batch_job_execution.CREATE_TIME) AS CREATED_TIME, batch_job_execution.END_TIME, batch_job_execution.STATUS FROM `batch_job_execution` INNER JOIN batch_job_instance ON batch_job_execution.JOB_INSTANCE_ID = batch_job_instance.JOB_INSTANCE_ID WHERE batch_job_execution.CREATE_TIME LIKE '%2016-12-05%' GROUP BY batch_job_instance.JOB_INSTANCE_ID ORDER BY MAX(batch_job_execution.CREATE_TIME) DESC
my Question, how i use that query in laravel? i am new in laravel, can someone help me? i need this for my project Thanks :)

You can run this SQL query as ot is if you had problem in converting in laravel format.
You can use :
DB::select(DB::RAW(your_sql_query)):
Hope this will help.

You can create a function within your model and query the data using the bellow format
public static function getJobs()
{
$jobs = DB::table('batch_job_execution')
->select(
DB::raw('
DISTINCT batch_job_instance.JOB_NAME,
MAX(batch_job_execution.CREATE_TIME) AS CREATED_TIME,
batch_job_execution.END_TIME,
batch_job_execution.STATUS
'
)
)
->join('batch_job_instance', 'batch_job_execution.JOB_INSTANCE_ID', '=', 'batch_job_instance.JOB_INSTANCE_ID')
->where('batch_job_execution', 'LIKE', '%2016-12-05%')
->groupBy('batch_job_instance.JOB_INSTANCE_ID')
->orderBy(DB::raw('MAX(batch_job_execution.CREATE_TIME)'),'DESC')
->get();
// ->toSql();
return $jobs;
}

Related

MySQL query to get combination data

First of all, sorry my english is not so good.
my expected result is i want to get data which (residence unit id =21300 and residence user id null) AND (residence_user_id=25106 and residence_unit_id=21300) in one query
PLS HELP ME. thanks!
MySQL Raw query :
SELECT * FROM table_name where residence_unit_id = 21300 AND (residence_user_id = 25106 OR residence_user_id is null);
Laravel eloquent query :
Model::where('residence_unit_id', 21300)->where(function($query) {
$query->where('residence_user_id',25106)>orWhereNull('residence_user_id');
});
Query :
DB::whereNull('residence_user_id')->orWhereIn('residence_user_id' , [25106])->where('residence_unit_id' , 213100)->get()

Laravel subquery query

I want to use subquery in query as select. But this code doesnt work.
$listed_waiting_approach = DB::table('be_medical_insurance_for_foreigners')
->join('be_product','be_product.id','=','be_medical_insurance_for_foreigners.product_id')
->join('be_status','be_status.id','=','be_medical_insurance_for_foreigners.payment_status_id')
->where('be_medical_insurance_for_foreigners.is_approved','=',false)
->where('be_medical_insurance_for_foreigners.is_active','=',true)
->where('be_medical_insurance_for_foreigners.payment_status_id','=',$payment_status_id1)
->where('be_medical_insurance_for_foreigners.order_status_id','=',$order_status_id1)
->select('be_medical_insurance_for_foreigners.*','be_product.name as productname','be_medical_insurance_for_foreigners.is_approved as approve','be_status.code as statuscode','**(SELECT code FROM be_status WHERE id=$payment_status_id1 ) as paymentname**')
->get();
You can use a DB::raw combine with a DB::select. That is something like
DB::select( DB::raw( " ... ") )
You can also use selectRaw:
DB::table('be_medical_insurance_for_foreigners')
->selectRaw("be_medical_insurance_for_foreigners.*, be_product.name as productname, be_medical_insurance_for_foreigners.is_approved as approve, be_status.code as statuscode, (SELECT code FROM be_status WHERE id={$payment_status_id1}) as paymentname")
->get();

SQL request with GROUP BY and SUM in Eloquent

I just want make a simple sql request in my laravel application.
I'm not very comfortable with Eloquent aha.
This is the SQL request I want to make with eloquent :
select user_id, project_id, sum(hours)
FROM time_entries
WHERE spent_on BETWEEN '2018-04-10' AND '2018-12-10'
GROUP BY user_id, project_id
I've been trying something like :
TimeEntries::whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])->groupBy('user_id')->sum('hours');
(but you can see it's hopeless)
Use selectRaw().
TimeEntries::whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])->groupBy(['user_id', 'project_id'])->selectRaw('user_id , project_id, sum(hours) as sum')->get();
You can use the selectRaw function of Eloquent,
like this:
TimeEntries::selectRaw('user_id, project_id, sum(hours)')
->whereBetween(
'spent_on',
[ ($request->input('debut')), ($request->input('fin')) ]
)
->groupBy('user_id', 'project_id');
But be aware that not to binding variables in the selectRaw string parameter, it might cause SQL injection problem since it by-pass the escaping check
Below query will work:
$query = TimeEntries::query();
$query->selectRaw('user_id', 'project_id', sum(hours))
->whereRaw("spent_on >= '2018-04-10' and spent_on <= '2018-12-10'")
->groupBy('user_id')
->groupBy('project_id');
$result = $query->get();
Model->select(DB::raw('user_id, project_id,
SUM(hours)')->whereBetween...

Laravel Query Builder Statement return no result, but sql statement does

Laravel Query Builder
$data = CustomerPrepaid
::join('pos_sales', 'customer_prepaid.customer_id', '=', 'pos_sales.customer_id')
->join('pos_sales_product', 'pos_sales.pos_sales_code', '=', 'pos_sales_product.pos_sales_code')
->where('pos_sales_product.product_id', 'customer_prepaid.product_id')
->select('customer_prepaid.customer_id', 'customer_prepaid.created_at',
'pos_sales_product.pos_sales_product_code as reference_no',
'customer_prepaid.product_id', 'customer_prepaid.balance',
'last_used', 'expiry_date', 'customer_prepaid.amount as price')
->offset(($page-1)*$limit)->limit($limit)->get();
SQL
SELECT customer_prepaid.customer_id, customer_prepaid.created_at as purchase_date,
pos_sales_product.pos_sales_product_code as reference_no, customer_prepaid.product_id,
customer_prepaid.balance, customer_prepaid.amount*customer_prepaid.balance as value,
last_used, expiry_date, customer_prepaid.amount as price,
customer_prepaid.amount*customer_prepaid.balance as total
FROM customer_prepaid
JOIN pos_sales ON customer_prepaid.customer_id = pos_sales.customer_id
JOIN pos_sales_product ON pos_sales.pos_sales_code = pos_sales_product.pos_sales_code
WHERE pos_sales_product.product_id = customer_prepaid.product_id
The resulting SQL executed on the server returns the right result, but I get no eloquent result, why might that be?
Oh gosh, took me forever to realize you misused ->where.
Change your ->where to ->whereColumn:
$data = CustomerPrepaid
::join('pos_sales', 'customer_prepaid.customer_id', '=', 'pos_sales.customer_id')
->join('pos_sales_product', 'pos_sales.pos_sales_code', '=', 'pos_sales_product.pos_sales_code')
->whereColumn('pos_sales_product.product_id', 'customer_prepaid.product_id')
->select(
'customer_prepaid.customer_id',
'customer_prepaid.created_at',
'pos_sales_product.pos_sales_product_code as reference_no',
'customer_prepaid.product_id', 'customer_prepaid.balance',
'last_used', 'expiry_date', 'customer_prepaid.amount as price'
)
->offset(($page-1)*$limit)
->limit($limit)
->get();
You have to use whereColumn instead of where to make column comparison. Else it's expecting a third parameter value to be set.
Check the documentation on how to use whereColumn: https://laravel.com/docs/5.5/queries#where-clauses

Convert PostgreSQL to SqlAlchemy query

I have a simple query in PostgreSQL which I need to convert to SQLAlchemy.
SELECT table1.name,table2.ip,table2.info
FROM table1 LEFT OUTER JOIN table2
ON(table1.name=table2.hostname)
GROUP BY table1.name;
I have tried using this with no success:
session.query(table1.name
,table2.ip
,table2.info).distinct().join(table2).group_by(table1.name)
Can someone please help me with this?
Thanks in advance
Ishwar
Here's how you would do it using the Expression API
http://docs.sqlalchemy.org/en/latest/core/expression_api.html
Define your table, for example:
table1 = table('table1',
column('name', String())
)
table2 = table('table2',
column('ip', String()),
column('info', String()),
column('hostname', String()),
)
Compose your query, like:
my_query = select([table1.c.name,
table2.c.ip,
table2.c.info]
).select_from(
table1.outerjoin(table2, table1.c.name == table2.c.hostname)
).group_by(table1.c.name)
Execute your query, like:
db.execute(my_query)
It's not clear from your answer what the problem is, but my shoot at this query would be:
session.query(table1.name
,table2.ip
,table2.info)\
.outerjoin(table2)\
.group_by(table1.name)
I figured out the answer. I was actually missing the ON condition in query:
session.query(table1.name
,table2.ip
,table2.info
).distinct().outerjoin(table2 , table1.name=table2.hostname
).group_by(table1.name)
Thanks for help!