Fix n + 1 condition with database query