foreignKey handling code improved