Nested Query in Laravel 5.2 Query Builder Pulling MAX date - php

I'm trying to pulling a group of users who have not made a transaction since a specified date.
This is my query:
$notActive = DB::table('transactions')
->join('users','transaction.user_id', '=', 'users.user_id' )
->select(DB::raw('users.user_id, users.name, max(transaction.last_posted_date) AS lastDate'))
->groupBy('users.user_id')
->where('lastDate', '<', ''.$not.'');
return Datatables::of($notActive)
->make(true);
$not is the date value pulled in. This produces an ajax data-tables error. I've tried this multiple ways including putting a select statement for the max date in the where clause but it keeps throwing up errors. Is there a better way to query this data that I want? Thanks.

I figured it out! Using the having clause brought up those users who had transactions with dates less than the date that was being provided by the input field (i.e. Not Active Since)
$notActive = DB::table('transactions')
->join('users','transactions.user_id', '=', 'users.user_id' )
->select(DB::raw('users.user_id, users._name, max(transactions.last_posted_date) as last_posted_date'))
->groupBy('users.user_id')
->having('transactions.last_posted_date', '<', ''.$not.')');
return Datatables::of($latestTransactions)
->make(true);

Related

Retrieving the minimum and maximum Datetime value from a signle Date column in laravel eloquent query

I am working on retrieving records in group with date-time from my table called 'sales'
The expected output i wanted was to be in such rows
The starting date from the output is expected to give the first day record of the production group list i.e 2022-06-08, the ending day is for the last day ie 2022-0-22.
I have tried several queries in trying to get on to that but it all returns error.
here are some codes that i used
I saw this info from
https://docs.trifacta.com/display/SS/MAXDATE+Function
$this->sales = DB::table('sales')
->select(
\DB::raw('maxdate("s_date") as firstDay','mindate("sales.s_date") as lastDay', 'sum("qty") as totalAmount','sum("leaking") as totalExpenses'), 'sales.productions_pr_id'
)
->groupBy('productions_pr_id')
->get();
I have also used Max(date) format and all i get is erros.
$this->sales = DB::table('sales')
->select(
\DB::raw('max("s_date") as firstDay','min("sales.s_date") as lastDay', 'sum("qty") as totalAmount','sum("leaking") as totalExpenses'), 'sales.productions_pr_id'
)
->groupBy('productions_pr_id')
->get();
I have gone through quite some number of solution but couldn't find similar to my problem. I am only interested in query that will give me the first date of example production_pr_id =1
I was able to solve the problem with the following procedure
Removing the "" in \DB::raw('max("s_date") ie changing it to \DB::raw('max(s_date)
my final code looks like
$this->sales = DB::table('sales')
->select(
\DB::raw('min(sales.s_date) as firstDay'),\DB::raw('max(sales.s_date) as lastDay'), \DB::raw('sum((qty*100)-(leaking)) as totalAmount'),\DB::raw('sum(leaking) as totalExpenses'), 'sales.productions_pr_id'
)
->groupBy('sales.productions_pr_id')
->get();

How to convert this MySQL query to Laravel?

Here my MySQL query (work in phpMyAdmin) :
SELECT workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 AS total FROM `team` GROUP by workcenter ORDER BY total
then, i try in Laravel Sintax like this below (not work) :
$sql = Team::groupBy('workcenter')->select('workcenter', \DB::raw('(SUM(w1+w2+w3+w4)/ (COUNT(DISTINCT(teknisi))*30*4) )*100 AS total'))
->OrderBy('total', 'Desc')
->get();
When i run the laravel sintax, its doesn't show any errors, but the output is nothing..
Please anyone help me to convert the MySQL query to Laravel Sintax. Thank you!
I think you are close enough, however, this doesn't look like a correct way to group by with Eloquent ORM. Try using raw expressions, something like this might work:
$sql = DB::table('team')
->select(DB::raw('workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 as total'))
->orderBy('total', 'desc')
->groupBy('workcenter')
->get();
More about raw expressions here - https://laravel.com/docs/6.x/queries#raw-expressions
Whenever I want to convert SQL query to Laravel I always change one column name, the laravel error report will show your current query and u can compare it to the SQL query

Laravel where with 2 tables

I'm trying to check the another table to remove the matches from the results but unable to figure this out.
$value = people::select(array('people.blog_id'))
->join('blocks', 'people.user_id', '=', 'blocks.blocker')
->where('people.user_id', $user->id)
->where('blocks.blocker', '!=', 'people.user_id')
->get()
->toArray();
What I am trying to achieve, is to strip away the results when getting user_id from people where blocker is found as well in the blocks table, but the following returns an empty array.
As per laravel doc
You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method.
Change your query statement like bellow-
$articles = DB::table('people')
->join('blocks', 'people.user_id', '=', 'blocks.blocker')
->where('blocks.blocker', '<>', 'people.user_id')
->select('people.blog_id')
->get();
I think you should use right join here instead of simple join,
You can do it like.
$value = people::select(array('people.blog_id'))
->join('blocks', 'people.user_id', '=', 'blocks.blocker', 'right')
->where('people.user_id', $user->id)
->get()->toArray();
Please notice the fourth parameter in the join statement, this will include only the results where blocks will find.
Hope this will help

Laravel Query Buider Group By Not Getting All The Records

I am trying to get the data using groupBy on type field from my transaction table. I am using this query
DB::table($this->table)
->select()
->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())
->groupBy('type')
->get();
But it is not giving the complete records. There are more than 10 records in my table. But it is giving me only two. One for type=1 and another for type=2. It is selecting only on record from each type. I am expecting that i will get all the transactions based on condition grouped in two result set. Anyone know why it is happening?
Try to call Collection groupBy instead. Just put groupBy after get(). It should work.
DB::table($this->table)
->select()
->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())
->get()
->groupBy('type');
Faq::where('type','host')->get()->groupBy('category');

how to group by in db query builder to get the unique value?

Can someone help me to convert the below mysql to laravel db query builder or eloquent?Here is my mysql
SELECT max(created_at), jobseeker_id,call_reason,type_of_call
FROM calllogs
GROUP BY jobseeker_id
ORDER BY created_at DESC;
Here is my tries, but no luck yet.
$jobseekers =DB::table('calllogs')
->select(DB::raw("max('created_at'),jobseeker_id"))
->groupBy('jobseeker_id')
->orderBy('created_at','desc')
->get();
dd($jobseekers);
Please help me out.
$jobseekers =DB::table('calllogs')
->select(DB::raw("max(created_at),jobseeker_id"))
->groupBy('jobseeker_id')
->orderBy('created_at','desc')
->get();
Try with this code.
Only delete ' ' in max.
It will work well.
DB::table(calllogs)
->select(DB::raw('max(created_at) as max_created_at'),
'jobseeker_id','call_reason','type_of_call')
->groupBy('jobseeker_id')
->orderBy('max_created_at', 'DESC')
->get(); =>As a array.
->first(); => As a object.
Additionally, If you are using table joins see below.
->join('table_1','table_1.id','=','table_2.table_1_id')
->leftjoin('table_1','table_1.id','=','table_2.table_1_id')
->rightjoin('table_1','table_1.id','=','table_2.table_1_id')
ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'myapp.calllogs.created_at'
Two solution for that error
1.In config/database.php file make sql strict mode to false.
(or)
2. IN groupBy Clause add all your table colums.
example:
->groupBy('jobseeker_id','jobseeker_name','jobseeker_email')

Categories