I would like to ask on whats the best implementation on this one.
$users = User::with(['group', 'orders', 'comments'])->get()
$users->each(function($user) {
$user->comments->each(function($comment) {
// I know I can just add 'use' in the closure function to access the user again
// but let's just say that the user variable is not accessible at this point of the code.
// and the only way to access the user again is via $comment variable
// when I access user here. it tries to fetch in the database
$user = $comment->user;
});
});
my 1st solution was to add this line of code.
$user->comments->setRelation('user', $user);
this would fix the issue as the user would not fetch in the database anymore. but another problem arises. After setting the relation, the other eagerloaded user relationship will not be included in this level such as the $user->group, and $user->orders.
here's my 2nd solution
$users = User::with([
'group',
'orders',
'comments',
// trying to eager load the comments user again
'comments.user',
'comments.user.group',
'comments.user.orders'])->get()
this would work but I don't think this is the best solution. especially when I have a lot of nested relationship that I eagerloaded. I just limit it to 3 in the example to make it simplier.
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ESBhMC
via IFTTT
Aucun commentaire:
Enregistrer un commentaire