Fix various foreign key bugs during syncing