Jump to content


judge

Member Since 23 Mar 2016
Offline Last Active Apr 12 2016 10:43 AM
-----

#13949 Compound unique constraints

Posted judge on 23 March 2016 - 07:06 PM

Hi,

 

I had to add validation to my form input that checks that a compound constraint is not going to be violated. In this case I have two columns in my table 'team' and 'match' and the combination must be unique. So I coded this - it handles updates and adds:

...
        public function stats($op = null, $id = null) {
                $this->grocery_crud->set_table('stats');
                $this->grocery_crud->set_relation('team','teams','team');
                $this->grocery_crud->set_rules('team', 'Team', 'callback_unique_team_and_match['.$id.']');
                $output = $this->grocery_crud->render();

                $this->load->view('add_template.php',$output);
        }

        public function unique_team_and_match($team, $pk)
        {
                $match = $this->input->post('match');

                $this->db->where('team', $team);
                $this->db->where('match', $match);

                if ($pk != null) {
                        // This is an update
                        $this->db->where('id !=', $pk);
                }
                $result = $this->db->get('stats');

                if($result->num_rows() > 0)
                {
                        $this->form_validation->set_message('unique_team_and_match',"There is already an entry for team $team and match $match");
                        return false;
                }
                else
                {
                        return true;
                }
        }