Viacheslav1's avatar

Relations don't load sometimes

Hello people, i have a problem, when i try to load relations sometimes in some requests they are missing randomly, but if i don't use 'with' everything is absolutely fine. attachments has HasMany relationship. In 99% of the cases, the query does return the desired

$qb = Entry::query()->with([ 'folder', 'tags', 'location', 'share', 'attachments' => function (HasMany $q) { $q->orderBy('position', 'asc'); } ]);

this is code with bug

$qb = Entry::query();

this on is always works

But i understand its a lot of additional requests to base. Somebody knows how to fix it?

0 likes
8 replies
tykus's avatar

This would be a very strange behaviour from Eloquent; what have you done to diagnose the issue; are you logging the queries being executed and results? Do you see a different outcome whenever the relation apparently fail to load?

Viacheslav1's avatar

@tykus yes i used x debugger, and in some entries some relations just disappear, but if i request same entry without relations it's always works...

krisi_gjika's avatar

@Viacheslav1 assuming tag and attachments are HasMany or BelongsToMany relations they will always return eloquent collections even if empty. Can you show the full query?

krisi_gjika's avatar

@Viacheslav1 check if your missing tags or attachments are soft deleted or you have created another property with the same name that might be overwriting the relation collection. What is dd($entries_collection->attachments) when they are missing?

tykus's avatar

@Viacheslav1 there is a lot going on here that was not shared in the original question; which is very difficult to understand without proper code formatting.

What does applyFiltersToQuery do; what is the reason for extracting the paginated results to an Collection then converting to an array?

tykus's avatar

@Viacheslav1 not seeing anything that would unset eager-loading in either method. Is there any correlation between the filters/sorting that is set and the missing relations? Did you log the queries; for example, is there a tags query being executed whenever the result is missing the tags relation?

Please or to participate in this conversation.