How to pass value from database in laravel - php

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

Related

Laravel Database Eloquent Left Join Table

Hi I would like to ask is there any way to refer the 2 foreign key to 1 primary table id?
This is my code.
$job_postings = JobPosting::select(
'job_postings.id as job_posting_id',
'job_postings.qualifications',
'job_postings.created_at',
'job_postings.updated_at',
'job_postings.created_by',
'job_postings.approved_by',
'dealerships.dealership_name',
'departments.department_name',
'positions.position_name',
'users.name as created_by_name', (**This is the issue please help**)
'users.name as approved_by_name', (**This is the issue please help**)
DB::raw("case when job_postings.status = 0 then 'Pending' else 'Approved' end status"),
)
->leftJoin('dealerships', 'job_postings.dealership_id', '=', 'dealerships.id')
->leftJoin('departments', 'job_postings.department_id', '=', 'departments.id')
->leftJoin('positions', 'job_postings.position_id', '=', 'positions.id')
->leftJoin('users', 'job_postings.created_by', '=', 'users.id', 'job_postings.approved_by', '=', 'users.id')
->where('job_postings.id', $jp_id)
->get();
$data = [];
foreach($job_postings as $j => $job_posting){
$data[] = [
'job_posting_id' => $job_posting->job_posting_id,
'dealership_name' => $job_posting->dealership_name,
'department_name' => $job_posting->department_name,
'position_name' => $job_posting->position_name,
'qualifications' => $job_posting->qualifications,
'status' => $job_posting->status,
'created_by' => $job_posting->created_by_name,
'approved_by' => $job_posting->approved_by_name,
'created_at' => $job_posting->created_at->format('D, d M Y').date(' | h:i A', strtotime($job_posting->created_at)),
'updated_at' => $job_posting->updated_at->format('D, d M Y').date(' | h:i A', strtotime($job_posting->updated_at)),
];
}
Under the last leftJoin
->leftJoin('users', 'job_postings.created_by', '=', 'users.id', 'job_postings.approved_by', '=', 'users.id')
the approved_by is a foreign key pointing to users id and created_by is also a foreign key pointing to users id.
What I am aiming at is to get the name of the user but in separate reference.
Somewhat similar to this analogy .
'users.name = created_by as created_by_name',
'users.name = approved_by as approved_by_name',
approved_by = user.id => user.name
created_by = users.id => user.name
Thanks.
leftJoin('users','job_postings.created_by','=','users.id', 'job_postings.approved_by', '=', 'users.id')
Try this,
->leftJoin('users', function($join){ $join->on('users.id', '=', 'job_postings.created_by'); $join->on('users.id', '=', 'job_postings.approved_by'); })

Combine two queries into one query Laravel

I need to combine two queries into one so i can call it one time on my foreach inside a table in my blade view. I tried using merge() but it displays two separate queries. CountofPatents are all the patents that were submitted by a user and CountofApprovedPatents are the patents which has the status of "2". Here's how it looks now:
array 0 [person_id : 1
CountofApprovedPatents: 4
status: 2]
array 1 [person_id : 2
CountofApprovedPatents: 2
status: 2]
array 2 [person_id : 1
CountofPatents: 5]
array 3 [person_id : 2
CountofPatents: 4]
Here's how it's supposed to look like
array 0 [person_id : 1
CountofApprovedPatents: 4
CountofPatents: 5]
array 1 [person_id : 2
CountofApprovedPatents: 2
CountofPatents: 4]
Here's my code so far
AdminController
$start = $request->input('start');
$end = $request->input('end');
$approvedPatents = DB::table('patents')
->select('person_id', DB::raw('count(*) as CountofApprovedPatents'))
->where([
['status', '=', 2],
['date_approved', '>=', $start],
['date_approved', '<=', $end],
])
->groupBy('person_id')
->orderBy('status', 'desc')
->get();
$totalPatents = DB::table('patents')
->select('person_id', DB::raw('count(*) as CountofPatents'))
->where([
['date_approved', '>=', $start],
['date_approved', '<=', $end],
])
->groupBy('person_id')
->orderBy('status', 'desc')
->get();
$patents = $approvedPatents->merge($totalPatents);
$results = $patents->all();
return view('admin.patents.showPatents', compact('results',
'start', 'end'));
Is it possible to combine these two queries?
$results = DB::table('patents')
->union($approvedPatents)
->union($totalPatents)
->get();
What I think you are looking for is Unions.
It'll allow you to specify a query and then join it with the final query.
Eg.
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();
Try:
$approvedPatents = DB::table('patents')
->select('person_id', DB::raw('count(*) as CountofApprovedPatents, status'))
->where([
['status', '=', 2],
['date_approved', '>=', $start],
['date_approved', '<=', $end],
])
->groupBy('person_id')
->orderBy('status', 'desc')
$totalPatents = DB::table('patents')
->select('person_id', DB::raw('count(*) as CountofPatents'))
->where([
['date_approved', '>=', $start],
['date_approved', '<=', $end],
])
->groupBy('person_id')
->orderBy('status', 'desc')
->union($approvedPatents)
->get();
Otherwise you could be looking for Joins - worth a look at the docs :)
Unions: https://laravel.com/docs/5.8/queries#unions
Joins: https://laravel.com/docs/5.8/queries#joins
You can use MySQL's IF condition in your raw selection of columns.
$results = DB::table('patents')
->select('person_id',
DB::raw('sum(IF(status = 2,1,0)) as CountofApprovedPatents'),
DB::raw('count(*) as CountofPatents')
->where([
['date_approved', '>=', $start],
['date_approved', '<=', $end],
])
->groupBy('person_id')
->orderBy('status', 'desc')
->get();
The above IF condition in sum() adds 1 to the result if current row's status is 2, else it adds 0 which effectively doesn't break the sum.

Laravel 5 – querying items by many-to-many related model

I've got a following many-to-many relation:
attendees - attendee_tag - tag
Now I want to filter attendees based on some tag value, so I've created this solution, which works well:
$attendees = Attendee::whereHas('tags', function ($q) {
$q->where([
['attendee_tag.tag_id', '=', '6'],
['attendee_tag.value_string', '=', 'Summer ticket']
})->with(['tags' => function($q) {
$q->select('tags.id', 'value_type', 'attendee_tag.value_string', 'attendee_tag.value_int');
}])->paginate($pagination);
But I can't figure out, how to filter attendees based on more than 1 tag ... I've tried this, but it doesn't work:
$attendees = Attendee::whereHas('tags', function ($q) {
$q->where([
['attendee_tag.tag_id', '=', '6'],
['attendee_tag.value_string', '=', 'Summer ticket']
])->where([
['attendee_tag.tag_id', '=', '13'],
['attendee_tag.value_string', '=', 5]
]);
})->with(['tags' => function($q) {
$q->select('tags.id', 'value_type', 'attendee_tag.value_string', 'attendee_tag.value_int');
}])->paginate($pagination);
Any help would be highly appreciated! :)
Maybe with separating the whereHas :
$attendees = Attendee::whereHas('tags', function ($q0) {
$q0->where([
['attendee_tag.tag_id', '=', '6'],
['attendee_tag.value_string', '=', 'Summer ticket']
]);
})->whereHas('tags', function ($q1) {
$q1->where([
['attendee_tag.tag_id', '=', '13'],
['attendee_tag.value_string', '=', 5]
]);
})->with(['tags' => function($q) {
$q->select('tags.id', 'value_type', 'attendee_tag.value_string', 'attendee_tag.value_int');
}])->paginate($pagination);

Querying in Laravel doesn't query the correct result

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();

Laravel Eloquent Count multip

I currently have:
$emails = Email::select('username', DB::raw('count(*) as total'))
->groupBy('username')
->get();
Returning:
{'username' => 'example', 'total'=>'120' }
What I trying to do is to also get a count of a certain row value, where row value is equal to 1, to obtain:
{'username' => 'example', 'total'=>'120', 'sent' => '23' }
Like a :
DB::raw('count(sentitems) as sent WHERE sentitems = 1')
but of course it won't work this way .
If I understand you correctly, you mean something like this:
$emails = Email::select('username', DB::raw('count(*) as total'), DB::raw('count(case sentitems when 1 then 1 else null end) as sent')))
->groupBy('username')
->get();
What can the row value be if it isn't 1? If the only possible values are 0 and 1, you can simply use sum(sentitems). If other values are possible, you do sum(if(sentitems = 1, 1, 0))

Categories