I am trying to do the following query model in Laravel:
$num_stamps = Groupsheetstamp::where('status', '=', 'active')
->where('user_id', '=', $user->id)
->whereGroup_sheet_id($sheet->id)
->orWhere(function ($query) use ($sheet, $user) {
$query->where('original_group_sheet_id', $sheet->id);
})
->get();
However, this still returns all groupstamps that have a status of inactive, and it completely looks over the where clause for user_id.
What am I doing wrong in the query model, since it isn't querying the correct result back?
An example output from the query could be the following, with user id = 7 and sheet id = 12
"id" => 23
"group_sheet_id" => 12
"groupsheet_id" => 12
"group_id" => 3
"original_group_sheet_id" => 12
"user_id" => 1
"comment" => ""
"status" => "inactive"
"start_time" => "2017-03-16 17:09:06"
"end_time" => "2017-03-16 23:06:39"
"stamp_duration" => 6
"hours" => 0
"minutes" => 0
"themonth" => "03.17"
"manual_time" => ""
"created_at" => "2017-03-16 23:06:33"
"updated_at" => "2017-03-16 22:09:06"
It depends on what exactly result you're expecting. If you want to to search by group or by relation, you should use the closure. Just an example:
$num_stamps = Groupsheetstamp::where('status', 'active')
->where('user_id', $user->id)
->where(function($q) use ($sheet, $user) {
$q->where('group_sheet_id', $sheet->id)
->orWhere('original_group_sheet_id', $sheet->id);
})
->get();
https://laravel.com/docs/5.4/queries#parameter-grouping
try this
$num_stamps = Groupsheetstamp::where('status', '=', 'active')
->where('user_id', '=', $user->id)
->where('group_sheet_id',$sheet->id)
->orWhere(function ($query) use ($sheet, $user) {
$query->where('original_group_sheet_id', $sheet->id);
})
->get();
Related
How to filter created_at with month and year in Laravel's updateOrCreate()?
$statistik = Statistik::updateOrCreate(
[
'kode_kantor' => $map->kode_kantor,
'created_at' => whereYear('created_at', '=', date('Y-m-d')),
'created_at' => whereMonth('created_at', '=', date('Y-m-d'))
]
)->increment('poin_kunjungan');
What you are looking for cannot be done by updateOrCreate(). You would have to do a manual check. For example:
$statistik = Statistik::where('kode_kantor', $map->kode_kantor)
->whereYear('created_at', '=', date('Y-m-d'))
->whereMonth('created_at', '=', date('Y-m-d'))
->first();
if(! $statistik) {
$statistik = Statistik::create([
'kode_kantor' => $map->kode_kantor
]);
}
$statistik->increment('poin_kunjungan');
I am trying to get following data from table
Count of registered users in each date
User details
I am trying following script to get that
$users = User::select(DB::raw('count(id) as agents, left(DATE(created_at),10) as registeredDate'))
->whereHas('roles', function($q){
$q->where('name', '=', 'agent');
})
->offset($start)
->limit($limit)
->orderBy($order,'DESC')
->groupBy('registeredDate')
->get();
Above query is returning the Count of registered users in each date
if($users){
foreach($users as $r){
$nestedData['agents'] = $r->agents;
$nestedData['date'] = date('d M Y',strtotime($r->registeredDate));
$data[] = $nestedData;
}
}
But I wanted to get users details also in the same query. My desired output is
'data' => [
[
"agents" => "13",
"date" => "12 Jan 2019",
"nested_data" => [
[
'full_name' => 'john',
'status' => 'active',
'email' => 'john#gmail.com',
],
[
'full_name' => 'John',
'status' => 'active',
'email' => 'john2#gmail.com',
]
]
]
]
Can someone kindly guide me how to achieve it. I would like to appreciate. Thanks
Change your query as:
$users = User::select(DB::raw('count(id) as agents, left(DATE(created_at),10) as registeredDate'))
->whereHas('roles', function($q){
$q->where('name', '=', 'agent');
})
->offset($start)
->limit($limit)
->orderBy($order,'DESC')
->get();
Change your foreach loop as:
if($users){
foreach($users as $user){
$date = date('d M Y',strtotime($r->registeredDate));
$data[$date]['date'] = $date;
$data[$date]['nestedData'][] = ['first_name' => $user->first_name, 'status' => $user->status, 'email' => $user->email];
$data[$date]['agents'] = count($data[$date]['nestedData']);
}
}
How can I pass the value of lead_id to my attendance table?
Here is the code from my controller
$scores = Score::with('lead','subject')->get()->groupBy('lead_id');
I want to pass $scores here:
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '=', 'P')
->whereBetween('days', [$from,$to])
->groupBy('status')
**->where('lead_id','=',$scores)**
->get();
Both table Score and Attendance has lead_id is it possible to connect them? i want to perform total base on the lead_id from score table is equal to attendance table. with my code i'm getting this empty array
try this:
$scores = Score::with('lead','subject')->get();
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '=', 'P')
->whereBetween('days', [$from,$to])
->groupBy('status')
->whereIn('lead_id', array_column($scores->toArray(), 'lead_id'))
->get();
where condition in eloquent expects a string/integer value to be pased and not a collection as you are trying to pass it.
After you get the results from this query:
they should be grouped by keys like:
$scores = Score::with('lead','subject')->get()->groupBy('lead_id');
Collection{
1 => Collection{somedata},
2 => Collection{somedata},
}
So i pressume you need only the keys from this collection:
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '=', 'P')
->whereBetween('days', [$from,$to])
->groupBy('status')
->whereIn('lead_id',$scores->pluck('lead_id')->toArray())
->get();
this is the result of DD$scores
"id" => 62
"subject_id" => 4
"lead_id" => 5
"uuid" => "36c850d0-9ec9-11e8-85e1-cdb65cbc1965"
"created_at" => "2018-08-13 07:19:27"
"updated_at" => "2018-08-13 07:19:27"
]
the total is not there
I am trying to increase the speed of my Laravel 5.4 sql query by using joins, which I've never used before. I currently have the query working and returning results, my issue is that I get like each results around 8 times. Ex: I get the same 2001 Chevrolet Silverado 8 times in my array. If anybody could help me out I would really appreciate it. Thanks
My query + collection:
$tmp = DB::table('inventories'
)->join(
'vehicles', 'vehicles.id', '=', 'inventories.id'
)->join(
'vimages', 'vimages.vehicle_id', '=', 'inventories.id'
)->where(
'inventories.dealer_id', '=', $dealer_id
)->where(
'inventories.is_active', '=', 1
)->where(
'inventories.is_deleted','=', 0
)->select(
'inventories.stock_number','inventories.vehicle_id','vehicles.year','vehicles.make','vehicles.model','vehicles.vin','inventories.vehicle_status',
'inventories.cost','inventories.search_meta','vimages.name'
);
$data = collect();
$pmt = $tmp->get();
// return json_encode( $pmt );
// logger( sprintf('# of rows returned: %s', $pmt->count() ) );
$pmt->each( function($row) use(&$data) {
// logger( sprintf('Row : %s', $row->toJson() ));
$data->push( array(
'stock_number' => $row->stock_number,
'vehicle_id' => $row->vehicle_id,
'year' => $row->year,
'make' => $row->make,
'model' => $row->model,
// 'trim' => $row->trim,
'vin' => $row->vin,
'status' => $row->vehicle_status,
// 'purchase_price' => $row->purchase_price,
'cost' => $row->cost,
// 'retail_price' => $row->retail_price,
'search_meta' => $row->search_meta,
// 'images' => $row->getFirstImage()
'images' => $row->name
// 'interior_color' => $row->vehicle()->first()->interior_color,
// 'exterior_color' => $row->vehicle()->first()->exterior_color,
// 'firstImg' => $row->getFirstImage()
// 'images' => Vimage::select('vehicle_id','name'
// )->where(
// 'dealer_id', '=', $row->dealer_id
// )->where(
// 'vehicle_id', '=', $row->vehicle_id
// )->limit(1)->get()
));
});
Example of my array:
https://i.imgur.com/FOphST8.png
I don't see your db table but I think there is problem in first join statment:
you should use
->join('vehicles', 'vehicles.id', '=', 'inventories.vehicle_id' )
instead of
->join('vehicles', 'vehicles.id', '=', 'inventories.id' )
also second join should be like
->join('vimages', 'vimages.vehicle_id', '=', 'vehicles.id')
instead of
->join('vimages', 'vimages.vehicle_id', '=', 'inventories.id')
It sounds trivial but this should work:
$tmp = DB::table('inventories'
)->join(
'vehicles', 'vehicles.id', '=', 'inventories.id'
)->join(
'vimages', 'vimages.vehicle_id', '=', 'inventories.id'
)->where(
'inventories.dealer_id', '=', $dealer_id
)->where(
'inventories.is_active', '=', 1
)->where(
'inventories.is_deleted','=', 0
)->selectRaw("DISTINCT inventories.stock_number, inventories.vehicle_id,
vehicles.year, vehicles.make, vehicles.model, vehicles.vin,
inventories.vehicle_status, inventories.cost,
inventories.search_meta, vimages.name"
);
Update: forgot to delete the single quotes in selectRaw
Figured it thanks to #Devon. Added another where statement to query to only get first image.
Thanks
)->where('vimages.sequence','=', 0
For example I have the following query which updates a new row:
$query->where('email', '=', $user->email)->where('card_uid', '=', $k)
->update( array('email' => $user->email, 'card_uid' => $k, 'have_quantity' => ($card->have_quantity+$v)) );
I'd like to retrieve the updated (or inserted) row. I tried the following but it doesn't work:
$row = $query->where('email', '=', $user->email)->where('card_uid', '=', $k)
->update( array('email' => $user->email, 'card_uid' => $k, 'have_quantity' => ($card->have_quantity+$v)) )
->get();
How can I retrieve the row I am updating or inserting easily?
You can try using the same query builder instance for the update first and then run the select query. (You can't do it the way you tried because update() returns the number of affected rows)
$query->where('email', '=', $user->email)->where('card_uid', '=', $k);
$query->update(array('email' => $user->email, 'card_uid' => $k, 'have_quantity' => ($card->have_quantity+$v)))
$row = $query->get();