Refactor whereHas to use via global scopes in Laravel - laravel-5

I've 2 models, CoreChallenge and Challenge. Below are relations between table.
I want to fetch Challenges which has core_challenges active. I tried to do putting global scope in CoreChallenge model, but when I'm getting null in relationship when Corechallenge is inactive.
I've done it this way
$challenges = Challenge::with('core_challenge')->whereHas('core_challenge', function($q){
$q->where('status', '=', 'active');
})->get();
I want to do it using global scopes
Global scope on CoreChallenge gives me null, but I want that it's parent (Challenge) should not load even, like in whereHas. Is there any way?

I have stumbled to the same approach, but when the table got bigger (core_challenges_table in your scenario), whereHas ended up being very slow (around 1min response time).
So I used a solution like this:
$ids = CoreChallenge::where('status', 'active')->pluck('id');
$challenges = Challenge::with('core_challenges')
->whereIn('core_challenge_id', $ids)
->get();
With this approach, my query reduced to 600~ms from 1min.
Which can be translated to Model scopes
class Challenge {
public function scopeActive($query) {
$activeIds = CoreChallenge::where('status', 'active')->pluck('id');
return $query->whereIn('core_challenge_id', $ids);
}
}
Challenge::with('core_challenges')->active()->get();

Related

Get all objects that exist in two collections

I'm building a Laravel page on which I want to show a list of lessons. Which lessons should be on the page is filtered by three criteria (of which all should be true):
The lesson is active, ie "where('active', true)". Simple enough.
The lesson is part of a track that the user has chosen. Models are set up with belongsToMany() (it is a many-to-many relationship), so I can get these lessons by a simple $track->lessons.
This is where it gets tricky. Some lessons should only be visible to users with certain titles (ie there is a many to many between titles and lessons). I can get the lessons with the correct title requirement using Auth::user()->title->lessons.
Question is how I get all this together. The best I've come up with this far is the following:
$title = Auth::user()->title;
$lessons = Lesson::where('active', true)
->whereIn('id', $track->lessons->pluck('id'))
->where(function ($query) use($title) {
$query->whereIn('id', $title->lessons->pluck('id'))->orWhere('limited_by_title', false);
})
->get();
...which is crap ugly, clearly suboptimal and (for some reason I really don't understand) also won't work (I don't get the lessons my title entitles me to in my list). Been struggling for quite some hours now, I get the feeling that I'm overcomplicating, first plucking id's and then using them in a whereIn() can't possibly be a good way of doing this.
So I can easily enough get a collection of lessons in the track, and I can get a collection of lessons belonging to the title, but how do I get all objects that exist in both those collections?
Using whereHas() is the answer to your concerns about plucking IDs. Instead of running additional queries to retrieve IDs, whereHas() will attach the constraint to the original query as a subquery on the related tables.
Breaking the query down to its parts:
1: Answered
2: Assuming the inverse of $track->lessons is $lesson->tracks, and $track is coming from code you didn't include:
$lessons = Lesson::whereHas('tracks', function ($query) use ($track) {
$query->where('id', $track->id);
})
3: Assuming the inverse of $title->lessons is $lesson->titles:
$lessons = Lesson::where(function ($query) use ($title) {
$query->whereHas('titles', function ($query) use ($title) {
$query->where('id', $title->id);
})
->orWhere('limited_by_title', false);
})
Combined back into one:
$track = ???;
$title = Auth::user()->title;
$lessons = Lesson::where('active', true)
->whereHas('tracks', function ($query) use ($track) {
$query->where('id', $track->id);
})
->where(function ($query) use ($title) {
$query->whereHas('titles', function ($query) use ($title) {
$query->where('id', $title->id);
})
->orWhere('limited_by_title', false);
})
->get();
If this still doesn't give the results you were expecting, you can examine the full query being run by replacing get() with toSql(). Sometimes working from the ORM as a starting point instead of the SQL can lead you down the wrong path. For even more detail to debug and understand the queries being run, you can enable query logging: https://laravel.com/docs/5.7/database#listening-for-query-events
intead of where use whereHas on "titles" relationship
$title = Auth::user()->title;
$lessons = Lesson::where('active', true)
->whereIn('id', $track->lessons->pluck('id'))
->whereHas('titles',function ($query) use($title) {
$query->whereIn('id', $title->pluck('id'))
->orWhere('limited_by_title', false);
})->get();
First of all complicated, really complicated. Your table structure needs serious modification to make it easier.
However, considering you don't want to go down that road, you could do it simpler by using join
Assuming you have following table structure:
users
titles (has user_id foreign key)
lessons (has title_id foreign key)
tracks (has lesson_id foreign key)
$trackName = $request->input('track_name');
$title = Auth::user()->title;
$lessons = Lesson::join('tracks', 'lessons.id', '=', 'tracks.lesson_id')
->join('titles', 'lessons.title_id', '=', 'titles.id')
->where('lessons.active', true)
->where('tracks.track_name', $trackName)
->where(function ($query) use($title) {
$query->where('titles.id', $title->id)->orWhere('lessons.limited_by_title', false);
});
dd($lessons);
That is of course if your users table and titles have one to one relationship otherwise pluck all title_ids and use whereIn instead of where for titles.id query.
I hope you have enough understanding of laravel framework to understand and implement this solution.
Sorry, I don't have enough time to proofread or give more details.
Good luck!
Good luck if you need pagination after that :p I doubt simple ->paginate() will work :D
I hope it helps

Where clause inside whereHas being ignored in Eloquent

Im trying to make a query using whereHas with eloquent. The query is like this:
$projects = Project::whereHas('investments', function($q) {
$q->where('status','=','paid');
})
->with('investments')
->get();
Im using Laravel 5.2 using a Postgres driver.
The Project model is:
public function investments()
{
return $this->hasMany('App\Investment');
}
The investments model has:
public function project() {
return $this->belongsTo('App\Project');
}
The projects table has fields id,fields...
The investments table has the fields id,project_id,status,created_at
My issue is that the query runs and returns a collection of the projects which have at least one investment, however the where clause inside the whereHas is ignored, because the resulting collection includes investments with status values different than paid.
Does anyone has any idea of what is going on?
I believe this is what you need
$projects = Project::whereHas('investments', function($q) {
$q->where('status','=','paid');
})->with(['investments' => function($q) {
$q->where('status','=','paid');
}])->get();
whereHas wil check all projects that have paid investments, with will eagerload all those investments.
You're confusing whereHas and with.
The with method will let you load the relationship only if the query returns true.
The whereHas method will let you get only the models which have the relationship which returns true to the query.
So you need to only use with and not mix with with whereHas:
$projects = Project::with(['investments' =>
function($query){ $query->where('status','=','paid'); }])
->get();
Try like this:
$projects = Project::with('investments')->whereHas('investments', function($q) {
$q->where('status','like','paid'); //strings are compared with wildcards.
})
->get();
Change the order. Use with() before the whereHas(). I had a similar problem few weeks ago. Btw, is the only real difference between the problem and the functional example that you made.

Laravel > nested eager load with restriction

Assumed we've got users, friends and restaurants. Don't want to go to deep into the Model and relationship setup.
While me as a user is logged in: How can I get all friends who are "customers" of the restaurant?
I've got this and it's already working:
$friends = array_dot(Auth::user()->friends()->select('users.id')->get());
$customers = Restaurant::with(['users' => function($query) use($friends) {
$query->whereIn('users.id', $friends);
}])->find(restaurant_id);
But is this even possible with a single query?
It sounds like you want to find all of your friends that have a relationship to the restaurant. If so, you're looking for whereHas(). General idea:
$restaurantId = 1;
$user = Auth::user();
$friendCustomers = $user->friends()->whereHas('restaurant', function ($query) use ($restaurantId) {
$query->where('id', $restaurant_id);
})->get();
You can read more about querying relations, and whereHas, here.

Laravel 5 Eager Loading with parameters

I'm working on a project with a bit of a complex model that has joins in its relations and also requires a parameter. It all works pretty well, except for when I need to eager load the relationship, as I couldn't figure out if there is a way to pass a parameter/variable to it.
The Controller
$template = Template::find($request->input('id'));
$this->output = $template->zones()->with('widgets_with_selected')->get();
The Model
public function widgets_with_selected($banner_id)
{
return $this->belongsToMany('App\Models\Widget', 'zone_has_widgets')
->leftJoin('banner_has_widgets', function($join) use($banner_id) {
$join->on('widgets.id', '=', 'banner_has_widgets.widget_id')
->where('banner_has_widgets.banner_id', '=', $banner_id);
})
->select('widgets.*', 'banner_has_widgets.banner_id');
}
This is returning a Missing argument error as the variable is not being passed.
I have resolved the issue by moving the logic to the controller, but I want to know if there is a way to keep the relationship in the model and just call it with a parameter.
Looking at the laravel code I dont think this is possible as you'd like to do it. You simply cant pass parameters to a with() call.
A possible workaround is to have an attribute on your model for $banner_id.
$template = Template::find($request->input('id'));
$template->banner_id = 1;
$this->output = $template->zones()->with('widgets_with_selected')->get();
Then change your relationship
public function widgets_with_selected()
{
return $this>belongsToMany('App\Models\Widget','zone_has_widgets')
->leftJoin('banner_has_widgets', function($join) use($this->banner_id) {
$join->on('widgets.id', '=', 'banner_has_widgets.widget_id')
->where('banner_has_widgets.banner_id', '=', $banner_id);
})
->select('widgets.*', 'banner_has_widgets.banner_id');
}
You could perhaps alter it a bit by passing the banner_id through a method. Sortof like this in your model:
public function setBanner($id) {
$this->banner_id = $id;
return $this;
}
Then you can do:
$template->setBanner($banner_id)->zones()->with('widgets_with_selected')->get();
Not sure if this works, and it's not really a clean solution but a hack.

Problems with eagerly loading constraints in Laravel 4 - a workaround?

I have 2 tables, Places and Users. Places can have many Users.
// in Place.php
public function users()
{
return $this->hasMany('User');
}
//in User.php
public function place()
{
return $this->belongsTo('Place');
}
and am trying to get only the Places that have at least one active and enabled User associated through a static method Place::locationsWithPeople().
public static function locationsWithPeople()
{
return Place::with(array('users' => function($query)
{
$query->where('enabled', '=', 1)->where('active', '=', 1);
}))->get();
}
This yields an HTTP 500. Removing the two wheres does not help.
This works, but of course it does not contain the two wheres:
return Place::has('users')->get();
Anyone can help? It seems totally analogous to the example in Laravel's documentation.
This works for me.
$place = new Place;
$array = $place->with(array('users' => function($query)
{
$query->where('enabled', 1)->where('active', 1);
}))->get();
var_dump($array->toArray());
Maybe because you are trying to use non-static methods statically?
It seems that the problem was caused by excessive resource consumption, leading the page to HTTP500 over resource exhaustion. Fixed by rewriting it through join statements.
Can you try this?
return Place::with(array('users' => function($query)
{
$query->where('enabled', '=', 1)->where('active', '=', 1);
}))->hasWith('users')->get();
Method hasWithis a scope that written by me. You can get scopeHasWith() from http://paste.laravel.com/13jb. This will work same as has() method but it will call eagerload closure before attach WHERE to query builder.
I think this can resolve your problem that used resource too much and you can WHERE them from eagerload closure. I had same problem as you that I want to query with relation but it send all records that match WHEREIN too and cause memory problem.

Resources