Move SQL logic from controller into model