laravel join query with two table each have two where condition - php

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

Related

OrderBy its not wokring on laravel

i have a problem when doing "orderBy" name product. here are my codes
$resume = Transaction::with(['product' => function ($q) {
$q->orderBy('name_product','ASC');
}])
->where('status', 'keluar')
->where('status', 'masuk')
->get();
but my code its not working... here is the output
result
Use the collection to sort instead. It allows for sorting based on a nested property.
$resume = Transaction::with('product')
->where('status', 'keluar')
->where('status', 'masuk')
->get()
->sortBy('product.name_product')
->values();
Because you are applying condition to product, not in transaction.
I have another suggestion use whereHas.
Transaction::whereHas('product', function($query) {
$query->->orderBy('name_product','ASC');
})->where('status', 'keluar')
->where('status', 'masuk')
->get();

Laravel - Filter query with another query

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

Laravel Collection Query, Where I am going wrong?

My tables looks like this
area_trip
|id|dispatch_id|trip_id|status|
equipment_trip
|equipment_id|trips_id|dispatch_id|
trips
|id|dispatch_id|status
I am trying to pass collection to my resource. Can someone check my query and tell me what I am doing wrong as following query returning all the data matches dispatch_id whether it matches equipment_id or not. Btw I am new to laravel.
return
Resources::collection(
area_trip::where('dispatch_id', $request->dispatch_id)
->where('status', 1)
->orWhere('status', 9)
->whereHas('equipment_trip', function($query) use ($request) {
$query->where('equipment_trip.equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());
Here is the relationship set up in area_trip model
public function equipment_trip()
{
return $this->belongsTo(equipment_trip::class, 'trip_id', 'trips_id');
}
I believe your whereHas sub query is incorrect also instead of where and orWhere use where in and you can define all statuses necessary, try this:
Resource::collection(area_trip::where('dispatch_id', $request>dispatch_id)
->whereIn('status', [1, 9])
->whereHas('equipment_trip', function($query) use ($request) {
return $query->where('equipment_id', '=', $request->equipment_id);
})
->with(['equipment_trip', 'createdBy', 'updatedBy', 'area', 'trips'])
->orderBy('tripStartDate', 'ASC')
->orderBy('status', 'ASC')
->get());

cant get the data I want from two different tables using Laravel

I have a table called instructor_class: user_id, class_id and I have another table classes: id, time, active.
I would like to show classes for a single user but only those classes that active is 0 or 1.
My current code looks like this:
return InstructorClass::with('classes.session')->where('user_id', '=', $userId)->get();
This code is displaying me everything, then I tried the following code:
$active = 1;
return InstructorClass::with(['classes' => function ($q) use ($active) {
$q->where('active', '=', $active); // '=' is optional
}])
->where('user_id', '=', $userId)
->get();
This again returns me same records, but of course the class property is null for each record, which at some point looks correct, but my point is if the 'active' field does not corresponds at the classes table do not show the record, seems like the where() stm within with() is optional..
I am kinda stuck here...
Would appreciate your help, opinions!
You can use ::has('classes') to only return the models that have related classes
return InstructorClass::has('classes')->with(['classes' => function ($q) use ($active) {
$q->where('active', $active);
}])
->where('user_id', '=', $userId)
->get();
Never thought it could be this simple:
return InstructorClass::with('classes.session')
->join('classes', 'classes.id', '=', 'instructor_class.class_id')
->where('classes.active', '=', 1)
->where('user_id', '=', $userId)
->get();

Laravel query builder count

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

Categories