How to combined duplicate row to one row in laravel 5.7 controller - laravel

I want to combined the duplicate row to one row and show the result in front end but i face some error please any one help .
time_session | day
------------ ----
1 saturday
2 friday
2 friday
3 wednessday
this is my controller code:
public function classSchedule()
{
$duplicates = DB::table('applications')
->join('batches','applications.time_session' ,'=','batches.id')
->select( 'applications.*' , 'batches.*')
->groupBy('applications.time_session')
->get();
return view('backEnd.classes.manageClass1',['duplicates'=>$duplicates]);}
this is my front end code:
<td> {{$duplicate->time_session }} </td>
time_session | day taking day
------------ ---- ----------
1 saturday 1
2 friday 2
3 wednessday 1
SQLSTATE[42000]: Syntax error or access violation: 1055 'pixelmetro.applications.id' isn't in GROUP BY (SQL: select `applications`.*, `batches`.* from `applications` inner join `batches` on `applications`.`time_session` = `batches`.`id` group by `applications`.`time_session`)
Actual out put :
https://www.facebook.com/photo.php?fbid=2317443465016247&set=pcb.442972496253366&type=3&theater&ifg=1

This 1055 error is a MySQL issue that can be resolved changing Laravel config. Go to config/database.php file and change mysql property strict from true to false. 'strict' => false,
If you don't want to change it, then you can add a new property modes
'modes' => [
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
]
And yeah don't forget to run the command php artisan config:cache after making changes.
To get desired result you need to use count.
$duplicates = DB::table('applications')
->join('batches','applications.time_session' ,'=','batches.id')
->select( 'applications.*' , 'batches.*', DB::raw('COUNT(applications.time_session) as counter')
->groupBy('applications.time_session')
->get();
In blade:
#foreach($duplicates as $duplicate)
<td>$duplicate->counter</td>
#endforeach

i think you have some miss conception on group by.if you group by with a certain column then you have to get others column with aggregate function.
in your case you made group by with (time_session) and you try to get all from the table that's why you got the error.
solution: you can make group by with both (time_session and day) then your problem will be solve.
sample code:
public function classSchedule()
{
$duplicates = DB::table('applications')
->join('batches','applications.time_session' ,'=','batches.id')
->select( 'applications.*' , 'batches.*')
->groupBy('applications.time_session')
->groupBy('applications.day')
->get();
return view('backEnd.classes.manageClass1',['duplicates'=>$duplicates]);}

Related

For Chart - Trying to Get data for last 30 days and add "0" if data is not available in particular date

I am trying to draw chart for Last 30 days from Today showing total milk quantity. I get last 30 days using - [0 => "2022-02-07" ----- 30 => "2022-03-09"]
$olddate = Carbon::today()->subDays(30)->toDateString();
$todaydate = Carbon::today()->toDateString();
Also get the Data for Database as below [ date" => "2022-03-01" "totalmilk" => "24.10" "daykey" => "01"................."date" => "2022-02-16" "totalmilk" => "22.90" "daykey" => "16"]
$rahul = Buffalomilkrecord::select(DB::raw('date'), DB::raw('sum(totalmilk) as totalmilk, DATE_FORMAT(date,"%d") as "daykey"'))
->whereBetween('date', [$olddate, $todaydate] )
->groupBy(DB::raw('date'))
->orderBy('date', 'desc')
->get();
BY Below code, trying to put "0" if data is not Available
$ddtest = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
foreach($rahul as $order)
{
$ddtest[$order->daykey-1] = $order->date;
}
The code is working fine except the start date he is taking the database date which is (2022-03-01) where it should start with "2022-02-07".
I think i am making mistake while getting "daykey". It is assigning daykey "1" to first data available in database which start from date ""2022-03-01" (as No data available from 07-02-2022 to 28-02-2022 in the database and it start from 1 March 2022.) where as it should start from "$olddate" that is ""2022-02-07"..
where did i am making the mistake.....Thanks in Advance

how to retrieve different names from same table with different ids on join laravel

I need to get names from destinations table for each from_destination_id and to_destination_id
as fromDestinationName and toDestinationName
$bookingTransfersData = DB::table('transfers as t')
->select('t.periodStart as periodStart', 't.periodEnd as periodEnd','t.days','t.transfer_id','t.cost_round_trip',
't.cost_one_way','t.status','d.destination_id as destinationId','d.name as destinationName', 't.type',
'tf.name as officeName', 'ag.name as agencyName', 'u.name as userName', 'v.name as vehicleName')
->join('destinations as d', function ($join){
$join->on('t.from_destination_id','=','d.destination_id')
->orOn('t.to_destination_id','=','d.destination_id');
})->join('vehicles as v','t.vehicle_id','=','v.vehicle_id')
->join('transfer_offices as tf','t.office_id','=','tf.transfer_office_id')
->join('agencies as ag','t.forAgency_id','=','ag.agency_id')
->join('users as u','t.addedBy_user_id','=','u.id')
->get();
i want to get the names of each id after this results
$searchResults = $bookingTransfersData
->where('periodStart','between', $periodStart && $periodEnd)
->where('periodEnd','between', $periodStart && $periodEnd)
->where('destinationName','=',$from_destination_name && $to_destination_name)->where('type','like', $type);
like:
$fromDestinationName = $searchResults->pluck('from_destination_id','destinationName')
->where('from_destination_id','=','destinationId');
but $fromDestinationName return an empty collection
please help :)
I solved it by removing this join:
->join('destinations as d', function ($join){
$join->on('t.from_destination_id','=','d.destination_id')
->orOn('t.to_destination_id','=','d.destination_id');
})
and add for each destionation_id a join to retrive each name
and this will not work if I don't add for table name that i joined two times as to name it new name like
'destinations as d1' and 'destinations as d2'
$bookingTransfersData = DB::table('transfers as t')
->select('t.periodStart as periodStart', 't.periodEnd as periodEnd','t.days','t.transfer_id','t.cost_round_trip',
't.cost_one_way','t.status','d1.destination_id as fromDestinationId','d1.name as fromDestinationName', 't.type',
't.to_destination_id','tf.name as officeName', 'ag.name as agencyName', 'u.name as userName', 'v.name as vehicleName',
't.from_destination_id', 'd2.destination_id as toDestinationId','d2.name as toDestinationName')
->join('destinations as d1','t.from_destination_id','=','d1.destination_id')
->join('destinations as d2','t.to_destination_id','=','d2.destination_id')
->join('vehicles as v','t.vehicle_id','=','v.vehicle_id')
->join('transfer_offices as tf','t.office_id','=','tf.transfer_office_id')
->join('agencies as ag','t.forAgency_id','=','ag.agency_id')
->join('users as u','t.addedBy_user_id','=','u.id')->get();
the problem solved :)

How to get last month record from databse in laravel?

i have a table remaining_bus_fees.
id | date | student_id | remaining_balance
-----------------------------------------------------
1 | 2019-04-05 | 1 | 500
2 | 2019-05-10 | 2 | 400
3 | 2019-05-13 | 3 | 300
Now i need how to get last month record against student_id. here is
query i am using. but this is not working for me.
$remain_fee = \DB::table('remaining_bus_fees')
->whereMonth('date', '<', Carbon::now()->subMonth()->month)
->where('student_id', '=', 2)->get();
Here is useful queries :
$today=DB::table('remaining_bus_fees')->whereRaw('Date(created_at) = CURDATE()')->where('student_id', 2)->get();
$yesterday= DB::table('remaining_bus_fees')->whereDate('created_at',Carbon::yesterday())->get();
$last_7_days= DB::table('remaining_bus_fees')->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();
$this_month=DB::table('remaining_bus_fees')->whereMonth('created_at',Carbon::now()->month)->whereYear('created_at', date('Y'))->where('student_id', 2)->get();
$last_month=DB::table('remaining_bus_fees')->whereMonth('created_at',Carbon::now()->subMonth()->format('m'))->whereYear('created_at', date('Y'))->where('student_id', 2)->get();
Change your code to this and it should work fine, you need to convert your Carbon::now() to date format as you will use whereDate here, it will consider only date.
$remain_fee = \DB::table('remaining_bus_fees')
->whereDate('date', '<', Carbon::now()->subMonth()->toDateString())
->where('student_id', '=', 2)->get();
Example in tinker
>>> App\User::whereDate('created_at', Carbon\Carbon::now()->subMonth()->toDateSt
ring())->get()
=> Illuminate\Database\Eloquent\Collection {#3120
all: [
App\User {#3114
id: 90,
name: "******",
email: "******#gmail.com",
created_at: "2019-05-01 06:17:47",
updated_at: "2019-05-02 00:28:18",
},
],
}
>>>
Try this out,
$remain_fee = \DB::table('remaining_bus_fees')
->whereMonth('date', '=', Carbon::now()->subMonth()->month)
->whereStudentId(2)->get();
At the minute your code is saying where date is "before a month ago" whereas it should be where the date is a month ago (i.e. remove <). Also, I would suggest adding the year to the query as well otherwise you'll start to get previous years results.
This should get you what you need:
$date = Carbon::now()->subMonth();
$remain_fee = \DB::table('remaining_bus_fees')
->whereMonth('date', $date->month)
->whereYear('date', $date->year)
->where('student_id', 2)
->get();

Sum in laravel db query

I need to get the Sum of ProductQTY groupBy ProductID while using join, I always get an error when using db::raw, attached here is my code
$pick_list_items = DB::table('pick_list_detail')
->where('pick_list_detail.pick_list_id',$id)
->join('sale_invoices', 'pick_list_detail.sale_invoice_id','=','sale_invoices.id')
->join('sale_invoice_detail', 'sale_invoice_detail.sale_invoice_id','=','pick_list_detail.sale_invoice_id')
->select(['pick_list_detail.sale_invoice_id', 'sale_invoice_detail.product_id', 'sale_invoice_detail.product_qty', 'sale_invoice_detail.uom', 'sale_invoice_detail.uom_factor'])
->sum('sale_invoice_detail.product_qty')
->groupBy('sale_invoice_detail.product_id')
->get();
I'm using laravel 5.4
Here is the error
(2/2) QueryException
SQLSTATE[42000]: Syntax error or access violation: 1055 'fdis.pick_list_detail.sale_invoice_id' isn't in GROUP BY (SQL: select
pick_list_detail.sale_invoice_id,
sale_invoice_detail.product_id,
sale_invoice_detail.product_qty, sale_invoice_detail.uom,
sale_invoice_detail.uom_factor from pick_list_detail inner join
sale_invoices on pick_list_detail.sale_invoice_id =
sale_invoices.id inner join sale_invoice_detail on
sale_invoice_detail.sale_invoice_id =
pick_list_detail.sale_invoice_id where
pick_list_detail.pick_list_id = 1 group by
sale_invoice_detail.product_id)
$sale_invoices = DB::table('pick_list_detail')
->select(DB::raw('sum(sale_invoice_detail.product_qty) as si_count, pick_list_detail.pick_list_id , sale_invoice_detail.product_id , sale_invoice_detail.uom, sale_invoice_detail.uom_factor '))
->where('pick_list_detail.pick_list_id',$id)
->join('sale_invoices', 'pick_list_detail.sale_invoice_id','=','sale_invoices.id')
->join('sale_invoice_detail', 'sale_invoice_detail.sale_invoice_id','=','pick_list_detail.sale_invoice_id')
->groupBy('pick_list_detail.pick_list_id')
->groupBy('sale_invoice_detail.product_id')
->groupBy('sale_invoice_detail.uom')
->groupBy('sale_invoice_detail.uom_factor')
->get();
Raw Query is my solution.

Laravel 5 where condition to get pass 30 days worth of records

I have a date column in the instances table with varchar datatype stored as d-m-Y. In my where condition I am trying to fetch records for just past 30 days only.
$backdate = Carbon::parse('-30 days')->toDateString();
$date30DaysBack = Carbon::parse($backdate)->format('d-m-Y');
$adverts = DB::table('adverts')
->where(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), '>=',$date30DaysBack)
The full query
$adverts = DB::table('adverts')
->select(DB::raw('(SELECT IF(ext = \'jpeg\', CONCAT(fullpath, \'_1.\', ext), (CONCAT(fullpath,\'.\',ext))) as fullpath FROM advertsstorage where uid_dir = adverts.ad_uid ORDER BY id ASC limit 1)as fullpath, adverts.*, domains.location,instances.date'))
->join('domains','adverts.domain', '=' ,'domains.domain')
->join('advertiser_domains','domains.id', '=' ,'advertiser_domains.domain_id')
->join('advertisers','advertiser_domains.advertiser_id', '=' ,'advertisers.u_id')
->join('instances','adverts.ad_uid','=','instances.ad_uid')
->join('urls','instances.u_id','=','urls.id')
->join('sites','urls.sites_id','=','sites.id')
->where('advertisers.u_id', '=',$advertiserID)
->where(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), '>=',Carbon::now()->subDays(30)->format('d-m-Y'))
->orderBy(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), 'DESC')
->get();
Did you try DATEDIFF method
$adverts = DB::table('adverts')
->select(DB::raw('(SELECT IF(ext = \'jpeg\', CONCAT(fullpath, \'_1.\', ext), (CONCAT(fullpath,\'.\',ext))) as fullpath FROM advertsstorage where uid_dir = adverts.ad_uid ORDER BY id ASC limit 1)as fullpath, adverts.*, domains.location,instances.date'))
->join('domains','adverts.domain', '=' ,'domains.domain')
->join('advertiser_domains','domains.id', '=' ,'advertiser_domains.domain_id')
->join('advertisers','advertiser_domains.advertiser_id', '=' ,'advertisers.u_id')
->join('instances','adverts.ad_uid','=','instances.ad_uid')
->join('urls','instances.u_id','=','urls.id')
->join('sites','urls.sites_id','=','sites.id')
->where('advertisers.u_id', '=',$advertiserID)
->where(DB::raw('DATEDIFF( now(), STR_TO_DATE(instances.date,"%d-%m-%Y") )'), '<=', 30)
->orderBy(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), 'DESC')
->get();
Have you checked out the Carbon docs?
You can use the subtraction modifier for this; Carbon::now()->subDays(30);.
Would look something like this in your code:
$adverts = DB::table('adverts')->where(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), '>=', Carbon::now()->subDays(30)->format('d-m-Y'))
Try this.
Carbon has subDays function by which you can get past 30 days data
$date30DaysBack= Carbon::now()->subDays(30)->format('d-m-Y');
$today = Carbon::now()->format('d-m-Y');
$adverts = DB::table('adverts')
->whereBetween(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'),[$date30DaysBack,$today])->get()

Resources