you can create key before the loop.

Also, please do one query instead of N where N is number of given permissions (do query before the loop)