Pretty simple question.
I have a query:
$submissions = Submission::where('removed', 0)
->where('deleted', 0)
->orderBy('created_at', 'desc')
->paginate(40);
I want my other query
$savedSubmissionArray = SavedSubmission::where('user_id', Auth::user()->id)->get('id');
to filter results based on $submissions by matching the id of the submission with the 'submission_id' field of the SavedSubmission.
My attempt at this was:
$submissions = DB::table('submissions')->where('removed', 0)
->where('deleted', 0)
->orderBy('created_at', 'desc')
->paginate(40);
$savedSubmissionArray = DB::table('SavedSubmission')->where('user_id', Auth::user()->id)
->joinSub($submissions, 'submissions', function ($join) {
$join->on('saved_submissions.submission_id', '=', 'submissions.id');
})
->get('id');
but I'm not entirely sure that joinsub was what I'm supposed to be using here, as it returns:
InvalidArgumentException No message
You can use something like this
$data = DB::table('submissions')
->join('saved_submissions', 'submissions.id', '=', 'saved_submissions.submission_id')
->where(['submissions.removed' =>0, 'saved_submissions.user_id' => Auth::user()->id'])
->select('fields you want to select')
->get();
Add more fields according to your needs in where clause to filter the results
Related
So with pure PHP and MySQL i can get away with filtering an query for example. $sql = select*from users; then i have the drop downs, country province and districts.
if a user selects nothing, click get report all users are displayed. If user select any from drop eg. country it should then narrow down the result based on country selected. user can also implement the same on all dropdowns.
So i am trying to archive the same with Laravel i will show you my code.
Already i have selected and joined tables and its bringing back my results. i have tried to add a where to the results if a dropdwon value is set but its then not giving me results like i expect
$results = DB::table('people')
->leftJoin('contacts', 'people.id', '=', 'contacts.person_id')
->leftJoin('provinces', 'contacts.province_id', '=', 'provinces.id')
->leftJoin('nationalities', 'people.nationality_id', '=', 'nationalities.id')
->leftJoin('districts', 'contacts.district_id', '=', 'districts.id')
->select('people.*', 'contacts.*', 'provinces.name AS province_name',
'nationalities.name AS nationality', 'districts.name AS district_name');
if (request()->has('nationality_id')) {
$nationality_id = request('nationality_id');
$results->where('people.nationality', '=', $nationality_id)->get();
}
return view('reports.index', compact('results', 'nationalities', 'provinces'));
i expect that if i select dropdown and like province it filters the collection with the selected value of province being selected.
you should edit this code:
if (request()->has('nationality_id')) {
$nationality_id = request('nationality_id');
$results = $results->where('people.nationality', '=', $nationality_id)->get();
}
To be this:
if ($nationality_id = request('nationality_id')) {
$results = $results->where('people.nationality', '=', $nationality_id);
}
$results = $results->get()
try this maybe it helps you
if (request()->has('nationality_id')) {
$nationality_id = request('nationality_id');
$results = DB::table('people')
->leftJoin('contacts', 'people.id', '=', 'contacts.person_id')
->leftJoin('provinces', 'contacts.province_id', '=', 'provinces.id')
->leftJoin('nationalities', 'people.nationality_id', '=', 'nationalities.id')
->leftJoin('districts', 'contacts.district_id', '=', 'districts.id')
->select('people.*', 'contacts.*', 'provinces.name AS province_name',
'nationalities.name AS nationality', 'districts.name AS district_name')
->where('people.nationality', '=', $nationality_id)->get();
}else{
$results = DB::table('people')
->leftJoin('contacts', 'people.id', '=', 'contacts.person_id')
->leftJoin('provinces', 'contacts.province_id', '=', 'provinces.id')
->leftJoin('nationalities', 'people.nationality_id', '=', 'nationalities.id')
->leftJoin('districts', 'contacts.district_id', '=', 'districts.id')
->select('people.*', 'contacts.*', 'provinces.name AS province_name',
'nationalities.name AS nationality', 'districts.name AS district_name')
->get();
}
You should rewrite $results variable:
//...
if (request()->has('nationality_id')) {
$nationality_id = request('nationality_id');
$results = $results->where('people.nationality', '=', $nationality_id)->get();
}
//...
Problem is with this line
$results->where('people.nationality', '=', $nationality_id)->get();
->get() method is returnin new Collection object, which you need to pass to another variable.
$results itslef is a Builderinstance.
Just change
$results->where('people.nationality', '=', $nationality_id)->get();
To
$results = $results->where('people.nationality', '=', $nationality_id)->get();
And you will get what you want.
this is my controller and i need to add one where condition on table chapters with is_enabled = 0
$module = $course->modules()
->with('chapters')
->join('course_student', 'course_student.module_id', '=', 'modules.id')
->select('*', DB::raw('course_student.module_id as id'))
->where('is_enabled', 1)
->where('course_student.student_id', $user->id)
->where('course_student.test_completed', 0)
->where('course_student.ends_on', '>', Carbon::now())
->orderBy('order')
->first();
You should use the whereHas method if you want conditional selection of relationships.
These methods allow you to add customized constraints to a
relationship constraint, such as checking the content of a comment
Relationships documentation
Leaving you with a code like:
$module = $course->modules()
->whereHas('chapters', function ($query) {
$query->where('is_enabled', 0);
})
->join('course_student', 'course_student.module_id', '=', 'modules.id')
->select('*', DB::raw('course_student.module_id as id'))
->where('is_enabled', 1)
->where('course_student.student_id', $user->id)
->where('course_student.test_completed', 0)
->where('course_student.ends_on', '>', Carbon::now())
->orderBy('order')
->first();
I want to filter my query and return only if the user hasRole "Premium" and limit the result to 10.
Along with this query is a count of records which Conversion has and sort it in DESC order by total column.
Right now I have a working query that returns the count of Conversion and with a User but without user filter Role.
// Model Conversion belongs to User
// $from & $end uses Carbon::createDate()
// Current code
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
->whereBetween('created_at', [$from,$end])
->where('type','code')
->where('action','generate')
->whereNotNull('parent_id')
->with('user')
->groupBy('user_id')
->orderBy('total', 'DESC')
->take(10)
->get();
// current result
foreach ($query as $q) {
$q->user->name; // To access user's name
$q->total; // To access total count
}
// I tried this but no luck
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
->whereBetween('created_at', [$from,$end])
->where('type','code')
->where('action','generate')
->whereNotNull('parent_id')
->with('user', function($q) {
$q->hasRole('Premium');
})
->groupBy('user_id')
->orderBy('total', 'DESC')
->take(10)
->get();
You need to use whereHas instead of with, like this:
->whereHas('user', function ($query) {
$query->where('role','Premium');
})
Use the whereHas() instead of with(). Also, you can't use hasRole() if it's not a local scope:
->whereHas('user.roles', function($q) {
$q->where('name', 'Premium');
})
I'm using Laravels query builder to retrieve a list of items with some filter options - I need to do a count inside of this query:
$f = DB::table('Likes')
->join('Freestyle', 'Likes.FreestyleID', '=', 'Freestyle.id')
->join('Beat', 'Freestyle.BeatId', '=', 'Beat.id')
->join('Track', 'Beat.TrackId', '=', 'Track.id')
->join('Genre', 'Track.GenreId', '=', 'Genre.id')
->select('Likes.freestyleID as likeFreestyleID', 'Freestyle.*', 'Beat.TrackId as UseMeForTrack',
'Genre.id as GenreID')
->where('Freestyle.Active', '1')
->where('Freestyle.created_at', '>', "$dateScope")
->whereNull('Freestyle.deleted_at')
->whereIn('GenreID', $request->genre)
->first();
To count the amount of times the 'FreestyleID' appears in the likes table.
is this possible? The data returned is perfect I just need the amount of likes a freestyle has, where the FreestyleID in the likes table is null.
Something like this :
$f = DB::table('Likes')
->join('Freestyle', 'Likes.FreestyleID', '=', 'Freestyle.id')
->join('Beat', 'Freestyle.BeatId', '=', 'Beat.id')
->join('Track', 'Beat.TrackId', '=', 'Track.id')
->join('Genre', 'Track.GenreId', '=', 'Genre.id')
->select('Likes.freestyleID as likeFreestyleID','count(Likes.FreestyleID)', 'Freestyle.*', 'Beat.TrackId as UseMeForTrack',
'Genre.id as GenreID')
->where('Freestyle.Active', '1')
->where('Freestyle.created_at', '>', "$dateScope")
->whereNull('Freestyle.deleted_at')
->whereIn('GenreID', $request->genre)
->first();
I think you should be able to use a raw expression like this:
$f = DB::table('Likes')
->join('Freestyle', 'Likes.FreestyleID', '=', 'Freestyle.id')
->join('Beat', 'Freestyle.BeatId', '=', 'Beat.id')
->join('Track', 'Beat.TrackId', '=', 'Track.id')
->join('Genre', 'Track.GenreId', '=', 'Genre.id')
->select(DB::raw('COUNT(likes.FreestyleID) as num_likes'), 'Likes.freestyleID as likeFreestyleID', 'Freestyle.*', 'Beat.TrackId as UseMeForTrack',
'Genre.id as GenreID')
->where('Freestyle.Active', '1')
->where('Freestyle.created_at', '>', "$dateScope")
->whereNull('Freestyle.deleted_at')
->whereIn('GenreID', $request->genre)
->groupBy('Freestyle.id')
->first();
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();