Laravel 5.2 DB Query - php

I am trying to use DB to build a query like so:
Get all Distributors belonging to the User with their Accounts that have Notes.
I cant wrap my head around that query. Here is what I had that works in that it gets spits out the info I need in one array but 2 issues: the note name overwrites the account name since they are both called that, and I cant pass in a $user-> to replace the 2
Working (kind of)
$user = Auth::user();
$accounts = DB::table('distributors')
->join('accounts', function ($join) {
$join->on('distributors.vip_abbv', '=', 'accounts.dist_abbv')
->where('distributors.user_id', '=', 2);
})
->join('notes', 'notes.account_id', '=', 'accounts.id')
->select('accounts.name', 'notes.*')
->get();
What I need
$user = Auth::user();
$accounts = DB::table('distributors')
->join('accounts', function ($join, $user) {
$join->on('distributors.vip_abbv', '=', 'accounts.dist_abbv')
->where('distributors.user_id', '=', $user->id);
})
->join('notes', 'notes.account_id', '=', 'accounts.id')
->select('accounts.name (this is overwritten. can I change it to come out account_name so it doesnt?)', 'notes.*')
->get();

Try this for account name:
->select('accounts.name as custom_account_name')
Hope this helps.

Try this:
$user = Auth::user();
DB::table('distributors')
->join('accounts', function ($join) use ($user) {
$join->on('distributors.vip_abbv', '=', 'accounts.dist_abbv')
->where('distributors.user_id', '=', $user->id);
})
->join('notes', 'notes.account_id', '=', 'accounts.id')
->select('accounts.name as account_name', 'notes.*')
->get();

Related

Data Duplication PHP and Laravel

below is my code that duplicates database entries, what could the problem be?
When I try to trigger the end point that fetches employees it duplicates the entries multiple times
$all_employees = Employee::with([
'department',
'sub_department',
'first_supervisor',
'second_supervisor',
'reportingTo',
])
->select(
'employees.*',
'attendance_times.start_time as attendance_time',
'cities.city',
'countries.country',
'pay_frequencies.frequency as pay_frequency',
'duty_types.name as duty_type',
'rate_types.name as rate_type',
'positions.name as position_name',
'departments.department as sub_department',
'supervisors.name as supervisor_name'
)
->leftJoin('positions', function ($join) {
return $join->on('employees.position_id', '=', 'positions.id');
})
->leftJoin('countries', function ($join) {
return $join->on('employees.country_id', '=', 'countries.id');
})
->leftJoin('supervisors', function ($join) {
return $join->on('employees.first_supervisor_id', '=', 'supervisors.id');
})
->leftJoin('cities', function ($join) {
return $join->on('employees.city_id', '=', 'cities.id');
})
->leftJoin('attendance_times', function ($join) {
return $join->on('employees.attendance_time_id', '=', 'attendance_times.id');
})
->leftJoin('departments', function ($join) {
return $join->on('employees.sub_department_id', '=', 'departments.id');
})
->leftJoin('pay_frequencies', function ($join) {
return $join->on('employees.pay_frequency_id', '=', 'pay_frequencies.id');
})
->leftJoin('duty_types', function ($join) {
return $join->on('employees.duty_type_id', '=', 'duty_types.id');
})
->leftJoin('rate_types', function ($join) {
return $join->on('employees.rate_type', '=', 'rate_types.id');
})
->orderBy('employees.id', 'DESC')
->get();
return $this->customSuccessResponseWithPayload($all_employees);
Use with('Relation') while getting One to Many relation's data, because if you use leftJoin, you will get all the relation's data again.
Example:
Every Employee has many attendance_times, so if you create an SQL Query which gets all Employees and joined the attendance_times, the returned data will contain a duplicated EMP data every time it has attendance_times.
Basically use ->with('Relation').
Try to use the distinct with the query to fetch non-repetitive data.
DB::table('table')
->select('job_id')
->distinct()
->get();
It can be solved by adding the groupBy(employees.id) at the end of the query that's how I solved it.

Laravel Query Sending Different Result For Same Problem

Hi I am trying to create a one on one messaging system on LARAVEL. It was working all fine until for some users it started showing different result then expected. And it happens only for some users.. What is wrong with this query
$id =$receiver->id;
$messages = Message::where(function ($query) use ($id) {
$query->where('user_id', '=', Auth::user()->id)
->where('receiver_id', '=', $id);
})->orWhere(function ($query) use ($id) {
$query->where('user_id', '=', $id)
->where('receiver_id', '=', Auth::user()->id);
})->get();
After I return $messages the result is like this...
Working Result: Messages are coming sequentially..
In View It shows like this..
Same Query Bad Result
In the view you can see date are not aligned in order
I really can't figure out what went wrong if you can help I would really appreciate..
Your date is casting as UTC with ISO-8601 format, but I think date is not related with your issue, if you are not ordering with timestamp.
I suggest you to use orderBy with id, it can solve your issue easily :
$messages = Message::where(function ($query) use ($id) {
$query->where('user_id', '=', Auth::user()->id)
->where('receiver_id', '=', $id);
})->orWhere(function ($query) use ($id) {
$query->where('user_id', '=', $id)
->where('receiver_id', '=', Auth::user()->id);
})
->orderBy('id', 'ASC')
->get();

Inner query with use variable

I am new to laravel and I am trying to retrieve data from three tables because the user enters 3 information then I use its to determine the row to check login
so I use this way but not work!
I do not know how to send variables in SQL
DB::table('members')
->join(DB::raw('(SELECT FROM members_courses_assign WHERE referenceNumber=>$coursenum,termkey=>$semester) courseA'), function($join) {
$join->on('members.externalPersonKey', '=', 'courseA.externalPersonKey');
})->join(DB::raw('(SELECT courses FROM WHERE referenceNumber=>$coursenum,termkey=>$semester) coursecc '), function($join) {
$join->on('courseA.referenceNumber', '=', 'coursecc.referenceNumber');
})
->where(['jobID' => $jobid])->get();
Try this :
->where('jobID',$jobid)->get();
Here in Laravel Documentation you can find all you need to know about query builder.
To pass variable to inner query (Anonymous functions) you have to pass it with use keyword as described in docs
$yourVariable= "";
DB::table('members')
->join(DB::raw('(SELECT FROM members_courses_assign WHERE referenceNumber=>$coursenum,termkey=>$semester) courseA'), function($join) use($yourVariable) {
$join->on('members.externalPersonKey', '=', 'courseA.externalPersonKey');
})->join(DB::raw('(SELECT courses FROM WHERE referenceNumber=>$coursenum,termkey=>$semester) coursecc '), function($join) use($yourVariable) {
$join->on('courseA.referenceNumber', '=', 'coursecc.referenceNumber');
})
->where(['jobID' => $jobid])->get();
DB::table('members')
->join('members_courses_assign', function($join) use ($coursenum, $semester) {
$join->on('members.externalPersonKey', '=', 'members_courses_assign.externalPersonKey')
->where('referenceNumber', $coursenum)
->where('termkey', $semester);
})
->join('courses', function($join) use ($coursenum, $semester) {
$join->on('members_courses_assign.referenceNumber', '=', 'courses.referenceNumber')
->where('referenceNumber', $coursenum)
->where('termkey', $semester);
})
->where('jobID', $jobid)
->get();
You can refer to Query Builder's advanced join clauses here.

selects, joins, & wheres in Laravel

I'm trying to select specific columns from two tables however when I add the ->select() method into my query, I get an error.
If I leave out the ->select() method, I get a valid resultset and everything works, but adding the select breaks it. Sadly the error reported has nothing to do with the query and is useless to me.
Here is the code that works:
$notifications = DB::table('notifications')
->join('notifications_pivot', function($join)
{
$join->on('notifications.id', '=', 'notifications_pivot.notification_id')
->where('notifications_pivot.user_id', '=', Session::get('id'))
->where('notifications_pivot.is_read', '=', 'N');
})
->get();
Now here's the code that breaks:
$notifications = DB::table('notifications')
->join('notifications_pivot', function($join)
{
$join->on('notifications.id', '=', 'notifications_pivot.notification_id')
->where('notifications_pivot.user_id', '=', Session::get('id'))
->where('notifications_pivot.is_read', '=', 'N');
})
->select(DB::raw('notifications.id, notifications.subject, notifications.message, notifications.url,
notifications.start_date, notifications.end_date, notifications.access_role_id, notifications_pivot.id,
notifcations_pivot.notification_id, notifications_pivot.user_id, notifications_pivot.is_read'))
->get();
It's times like these when I wish I could just write straight SQL and parse the query!
Any suggestions?
Take out the DB::raw() and just pass the fields you want as parameters.
If that doesn't work, the Laravel log at app/storage/logs/laravel.log may provide more insight.
$notifications = DB::table('notifications')
->join('notifications_pivot', function($join)
{
$join->on('notifications.id', '=', 'notifications_pivot.notification_id')
->where('notifications_pivot.user_id', '=', Session::get('id'))
->where('notifications_pivot.is_read', '=', 'N');
})
->select('notifications.id', 'notifications.subject', 'notifications.message', 'notifications.url', 'notifications.start_date', 'notifications.end_date', 'notifications.access_role_id', 'notifications_pivot.id', 'notifcations_pivot.notification_id', 'notifications_pivot.user_id', 'notifications_pivot.is_read')
->get();

kohana query show latest record only

OK so basically I am creating a pm inbox in my kohana project
So far I have been able to retrieve the messages without an issue with this query
$messages = DB::select('users.username', 'users.id', 'profiles.profile_picture', 'messages.thread', 'messages.subject', 'messages.content', array('messages.id', 'mid'))->from('messages')->join('users', 'LEFT')->on('users.id', '=', 'messages.from_id')
->join('profiles', 'LEFT')->on('profiles.user_id', '=', 'messages.from_id')->where('messages.to_id', '=', $user)->and_where('messages.deleted', '=', '0')->execute();
My question is I would like to only show the last message if there is multiple from the same user. Should this be done in the query or with php when rendering the results.
I have a date column I think I can use for this, but I am not sure the best approach.
Thanks
$messages = DB::select('users.username', 'users.id', 'profiles.profile_picture', 'messages.thread', 'messages.subject', 'messages.content', array('messages.id', 'mid'))
->from('messages')
->join('users', 'LEFT')->on('users.id', '=', 'messages.from_id')
->join('profiles', 'LEFT')->on('profiles.user_id', '=', 'messages.from_id')
->where('messages.to_id', '=', $user)
->and_where('messages.deleted', '=', '0')
->order_by('messages.id', 'desc')
->offset(0)
->limit(1)
->execute();

Categories