Support MANY_MANY relations when using 'through' option

Resolves #3018.

This got mixed up with PR #3016. I could rebase it after accepting the previous PR to make code changes clearer or just check out two last commits, they're independent.