We used to go on military expeditions with the Messenger of Allah ﷺ without our wives, so we said, "Should we not castrate ourselves?" He forbade us from doing that, then permitted us to marry a woman in exchange for a garment for a fixed term.Then Abdullah recited, "O you who believe, do not forbid the good things that Allah has made lawful for you, and do not transgress. Indeed, Allah does not love the transgressors" [Maidah 5:87].
كنا نغزوا مع رسول الله ﷺ، ليس لنا نساء، فقلنا: ألا نستخصي؟ فنهانا عن ذلك، ثم رخص لنا أن ننكح المرأة بالثوب إلى أجل. ثم قرأ عبد الله: {يأيها الذين ءامنوا لا تحرموا طيبات ما أحل الله لكم ولا تعتدوا إن الله لا يحب المعتدين}.
Bukhari narrated it in the tafsir (4615), and Muslim in the marriage chapter (1404), both through Ismail bin Abu Khalid, from Qays, from Abdullah, who said, then he mentioned it. The wording given is that of Muslim, and Bukhari's wording is similar.