selects, joins, & wheres in Laravel - php

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

Related

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.

Laravel Query where All

I wondered how to make a Where All clause with Laravel
I'm trying to check if the episodes that a user saw are all the episodes of the series.
I'm using the WhereIn clause but i returns the results if i saw one episode of the serie.
$alleps get all the episodes of the serie
$seriessaw get all the episodes a user saw
Thank you for your answers !
$alleps = DB::table('episodes')
->select('episodes.id as ep_id')
->join('seasonsepisodes', 'episodes.id', '=', 'seasonsepisodes.episode_id')
->join('seriesseasons', 'seasonsepisodes.season_id', '=', 'seriesseasons.season_id')
->where('seriesseasons.series_id', '=', $id);
$seriesSaw = DB::table('usersepisodes')
->select('usersepisodes.episode_id as ep_id')
->where('usersepisodes.user_id', '=', Auth::user()->id)
->whereIn('usersepisodes.episode_id', $alleps)
->get();
I think you would need to set a having clause which would force records to only return if there's the same amount of records as there are amount of episodes.
$seriesSaw = DB::table('usersepisodes')
->select('usersepisodes.episode_id as ep_id')
->where('usersepisodes.user_id', '=', Auth::user()->id)
->whereIn('usersepisodes.episode_id', $alleps)
->having(\DB::raw('count(*)'), count($alleps))
->get();
You should note however that this would likely break if there's any possibility of having duplicates in the userepisodes table.
When you use WhereIn, you have to pass an array as the second parameter.
$alleps = DB::table('episodes')
->select('episodes.id as ep_id')
->join('seasonsepisodes', 'episodes.id', '=', 'seasonsepisodes.episode_id')
->join('seriesseasons', 'seasonsepisodes.season_id', '=', 'seriesseasons.season_id')
->where('seriesseasons.series_id', '=', $id)->get()->toArray();
$seriesSaw = DB::table('usersepisodes')
->select('usersepisodes.episode_id as ep_id')
->where('usersepisodes.user_id', '=', Auth::user()->id)
->whereIn('usersepisodes.episode_id', $alleps)
->get();

Using Distinct in Laravel Fluent

I have this join:
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->where('is_published', '=', 1)
But it unsurprisingly returns duplicate records, so I try to use distinct():
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->distinct()
->where('is_published', '=', 1)
but I want to use distinct() on a specific single field which I'd easily be able to do in SQL. It seems distinct() does not take parameters, i.e. I can't say distinct('volunteer.id').
Can anyone point me to how can I remove my duplicate records? I bet this is another forehead slapper for me.
In my project I tried distinct() and groupby() too and both of them worked:
//Distinct version.
Company_Customer_Product::where('Company_id', '=', $companyid)->distinct()->get(array('Customer_id'));
//Goup by version.
Company_Customer_Product::where('Company_id', '=', $companyid)->groupby('Customer_id')->get(array('Customer_id'));
According to this, distinct() should work in your case too, just use it with get():
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->distinct()
->where('is_published', '=', 1)
->get(array('volunteer.id'));
Otherwise you don't need distinct() when you use groupby() so you could just use:
Return DB::table('volunteer')
->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id')
->select(array('*','volunteer.id AS link_id'))
->group_by('volunteer.id')
->where('is_published', '=', 1)
->get(array('volunteer.id'));

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