Whats wrong with my code Laravel Callback function GroupBy Month - mysql

Im going to count my pallet_condition 0,1,2,3 and group it by month
but i always got an error like this please help whats wrong with my code.
something wrong with my date_format?
My Error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in group statement is ambiguous (SQL: select count(*) as aggregate from `liip_psrm` inner join `liip_psrm_items` on `liip_psrm`.`id` = `liip_psrm_items`.`psrm_items_id` where date(`liip_psrm_items`.`created_at`) >= 2018-10-09 and date(`liip_psrm_items`.`created_at`) <= 2019-01-31 and `liip_psrm`.`status` = 0 and `liip_psrm`.`customer_id` = 14 and `pallet_condition` = 0 group by WEEK(created_at) order by WEEK(created_at) asc)
My Callback function
$problem_condition_computations = function($condition) use ($psrm_maintenance, $start, $end, $customers){
return DB::table('liip_psrm')
->join('liip_psrm_items', 'liip_psrm.id', '=', 'liip_psrm_items.psrm_items_id')
->whereDate('liip_psrm_items.created_at', '>=', $start)
->whereDate('liip_psrm_items.created_at', '<=', $end)
->select(
DB::raw("DATE_FORMAT(liip_psrm_items.created_at, '%Y-%m-%d') AS dates
"))
->where('liip_psrm.status','=', 0)
->where('liip_psrm.customer_id','=',$customers)
->where('pallet_condition', $condition)
->groupBy('dates')
->count();
};

"dates" field you are using in groupBy is alias name, So it do not identifying it and not working as you are expecting.
Same as you used in Select
DB::raw("DATE_FORMAT(liip_psrm_items.created_at, '%Y-%m-%d') AS dates")
Put it in GroupBy
& It will work.
Hope, It will help, Let me know if you still find difficulties.

Related

Column not found: execption in laravel

I am working on some maintaince project where all are sql queries but i want to convert it in to laravel. Here is the below query :-
$members = Member::select('members.id','members.first_name',
'members.surname','members.username','members.password',
'members.email','user_access.active',
DB::raw('SUM( IF (user_access.active = "y", 1, 0) ) as acount'))
->join('user_access','user_access.member_id','=','members.id')
->where('special_access','=','n')
->groupby('user_access.member_id')
->having('acount','>','0')
->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderby('user_access.note','DESC')
->paginate(30);
Its giving me error when i execute the query. below the error in having clause
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'acount' in 'having clause' (SQL: select count(*) as aggregate from `members` inner join `user_access` on `user_access`.`member_id` = `members`.`id` where `special_access` = n group by `user_access`.`member_id` having `acount` > 0)
I guess something like this will help you.
$userAccess = DB::table('user_access')
->where('special_access','=','n')
->where('active','y')
->groupby('member_id');
Member::select([
'members.id',
'members.first_name',
'members.surname',
'members.username',
'members.password',
'members.email',
'user_access.active'
])->joinSub($userAccess, 'user_access', function($join){
$join->on('user_access.member_id', '=', 'members.id');
})->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderBy('user_access.note','asc')
->paginate(30);
OR
$members = Member::select([
'members.id',
'members.first_name',
'members.surname',
'members.username',
'members.password',
'members.email',
'user_access.active'
])->join('user_access', function($join){
$join->on('user_access.member_id', '=', 'members.id')->on('user_access.active', '=', DB::raw('"y"'));
})
->where('special_access','=','n')
->groupby('user_access.member_id')
->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderby('user_access.note','DESC')
->paginate(30);
As apokryfos said in the comments:
The paginator will attempt to get the count of the query and will remove all selects from it when doing so leading to this error.
If you just need records with user_access.active = "y" then you do not need to select them in the first place and then try to filter them out by HAVING

How to sum all aggregate value SQL- Laravel?

I want to some selected column. I have tried to sum for fee. But it throws an error:
Integrity constraint violation: 1052 Column 'service_fee' in field
list is ambiguous (SQL: select count(*) as aggregate from..........
I have tried below way. Can anybody help with this? Thanks in advance.
$events = Event::select($columns)->EventComplete()
->where('events.event_end_date', '<', $currentDate)
->where('events.have_balance', '>', 0)
->join('role_users_details as rud', 'events.promoter_id', '=', 'rud.id')
->join('transaction as tra', 'events.id', '=', 'tra.event_id', 'left outer')
->join(\DB::raw("(select tran.id as ttid, sum(tran.ticket_price) as total_amt, sum(tran.ticket_service_fee) as service_fee, tran.order_service_fee as order_service_fee,tran.order_service_fee_per as order_service_fee_per , count('ticket_order.*') as total_tickets
from `transaction` as `tran`
right join `ticket_order` on `tran`.`id` = `ticket_order`.`transaction_id`
where `ticket_order`.`status` = 1 group by `ttid`) as tt"), 'tt.ttid', '=', 'tra.id', 'left outer ')
->selectRaw('CONCAT_WS(" ", rud.first_name, rud.middle_name, rud.last_name) as promoter')
->selectRaw('sum(tt.total_amt) as tickets')
->selectRaw('sum(tt.service_fee) as service_fee')
->selectRaw('sum(tt.order_service_fee) as order_fee')
->selectRaw('sum(tt.order_service_fee_per) as order_fee_per')
->selectRaw('sum(tt.total_tickets) as total_tickets')
->selectRaw('(service_fee + order_fee + order_fee_per) as fee')
->selectRaw('FROM_UNIXTIME(events.event_end_date, "%Y/%m/%d %h:%i:%s") as ending_date')
->groupBy('events.id');
Could you just add all the sums together?
->selectRaw('sum(tt.service_fee) + sum(tt.order_service_fee) + sum(tt.order_service_fee_per) as fee')

Group by month producing error in laravel controller

I am trying to execute mysql query
SELECT COUNT( * ) FROM `Mytable` WHERE `col1` = 'value' GROUP BY MONTH(Date_time)
Laravel statement for the same is :
DB::table('Mytable')->where('col1','value')->GroupBy(MONTH('Date_time'))->count();
As query is fine but getting error :
Call to undefined function App\Http\Controllers\MONTH()
Any suggestion will be helpful
Instead of:
->GroupBy(MONTH('Date_time'))
try
->groupBy(DB::raw("MONTH('Date_time')"))
as MONTH() is a mysql function, not laravel function.
This would be your code:
DB::table('Mytable')->where('col1','value')
->groupBy(function($date) {
return Carbon::parse($date->Date_time)->format('m'); // grouping by months
})
->count();
Hope this works!

Eloquent: "WHERE (equals statement) AND (LIKE statement)"

I basically want to do:
select * from request where id = 1 and created_at like (today's date);
but using eloquent.
I tried:
$query = m_requests::where(['id' => Auth::User()->id, "created_at", "like", "%".date("Y-m-d")."%"]);
but that returns the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown
column '0' in 'where clause' (SQL: select * from
from `request` where (`id` = 1 and `0` = created_at
and `1` = like and `2` = %2016-04-22%))
Does anyone know how I could achieve what I am trying to do?
In summary:
I want the id to equal the id requested, but I want the date to be "LIKE" today's date (This is because I'm only interested in the date it was created and not the time it was created).
Cheers
Try this, it should work:
m_requests::where('id', '=', Auth::user()->id)
->where('created_at', 'LIKE', '%'.date("Y-m-d").'%');

MySQL PDO has no errors, but not pulling data

Something funky is going on with my MySQL PDO query.
If I pass in an array of values, it does not.
If I don't pass in the arrays it works.
I know this because I get a PDO error 0000, but when I run
$num_events_months = $result_events_months->rowCount();
it only returns a value if the values are hard-coded into the query.
I'm just not sure what I'm doing wrong?
The following DOES NOT work:
$query_events_months = "SELECT DATE_FORMAT(event_date, '%Y-%m') AS event_month_year, DATE_FORMAT(event_date, '%M') AS event_month_name FROM Events WHERE event_date >= :current_date AND status = :status GROUP BY event_month_year";
$result_events_months = $conn->prepare($query_events_months);
$result_events_months->execute(array(':current_date'=>'2014-10-01',':status'=>'published'));
The following DOES work:
$query_events_months = "SELECT DATE_FORMAT(event_date, '%Y-%m') AS event_month_year, DATE_FORMAT(event_date, '%M') AS event_month_name FROM Events WHERE event_date >= '2014-10-01' AND status = 'published' GROUP BY event_month_year";
$result_events_months = $conn->prepare($query_events_months);
$result_events_months->execute(array(':current_date'=>'2014-10-01',
':status'=>'published'));
I'm just not sure what I'm doing wrong?
PDO ERROR 000 is the value returned when a query executed successfully.
You should only print when it fails, otherwise you should ignore.
In your case something along the lines:
if(!$result_events_months->execute(array(...))){
var_dump($result_events_months->errorInfo()); //not outside of the failure block
}else{
var_dump($result_events_months->fetchAll());
}