php - Load relationships before foreach loop
Get the solution ↓↓↓I have aUser
model that does have many Networks. EachNetwork
does have many Lists.
I have this code in theUser
model that is really slow:
foreach ($this->networks as $network) {
if ($myCondition) {
foreach ($network->lists()->get()->lists('id')->toArray() as $newId) {
$ids[] = $newId;
}
}
}
I wonder if there is a way to load all lists of all networks before the 2 foreach loops.
Answer
Solution:
This may speed it up, although I'm not certain:
$this->networks()->with('lists')->get()->pluck('lists')->flatten()->pluck('id')
Also if it isn't a many to many relationship you could consider putting user_id as a column in your 'lists' table if speed is really important
Answer
Solution:
This is lazy eager loading:
$this->networks->load('lists');
That loaded thelists
relationship for all the networks.
If you just want this list of ids and don't need the actual records returned you can do that as well:
$ids = Lists::whereHas('network', function ($query) {
$query->whereIn('id', $this->networks->pluck('id'));
})->pluck('id');
If you want because Lists belongsTo Network you can go around the relationship:
$ids = Lists::whereIn('network_id', $this->networks->pluck('id'))
->pluck('id');
Answer
Solution:
Just keep code in User model. In controller, you can do:
$User->load('networks', function($q){
$q->with('lists');
});
There in:
'networks' and 'lists' is your relationship name.
Further: You can lazy load all your relation ship, in child by child.
$User->load('networks', function($q){
$q->with('lists', function($q1){
$q1->with('child_relationship_of_lists');
});
});
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: err_ossl_pem_no_start_line
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.