Post-Kemal Turkey has a history of military's interference in civil matters whenever there was even the slightest symptom that the government was showing sympathy towards religion. They even hanged one of the elected prime ministers (Adnan Menderes).
But, Ergodan seemed to have good control over the military from the beginning, even before the failed coup as he came to power in 2003 as a PM and coup was staged in 2016. That is a long time given that he was an Islamist from the beginning.
How did he make that happen?