[1.7.x] Fixed #22319 -- Fixed migration external dependencies when there are internal dependencies.

Backport of 0fd51cf0bd from master