Hello
Since I have the following table:
DROP TABLE IF EXISTS 'tb_conta';
CREATE TABLE IF NOT EXISTS 'tb_conta' (
'id' INT(11) NOT NULL AUTO_INCREMENT,
'nome' VARCHAR(255) NOT NULL,
'tipo' TINYINT(1) NOT NULL DEFAULT 1,
'padrao' BIT(1) NOT NULL DEFAULT 1,
PRIMARY KEY ('id'))
ENGINE=InnoDB
DEFAULT CHARSET=utf8;
I need to make sure that regardless of the amount of rows written in this table, there is only one result in the padrao
field whose value is equal to true
Both new insertion and update.
Scenario:
If when entering a new record and the value of the field padrao
is equal to true
, then automatically all other values already registered in the table, become false
, the same goes for updates
. >
Add and Update Functions
// add
public function add($dados)
{
$conta = [
'nome' => $dados->nome,
'tipo' => $dados->tipo,
'padrao' => $dados->padrao,
];
$this->db->insert($this->tabela, $conta);
}
// edit
public function edit($where, $dados)
{
$conta = [
'nome' => $dados->nome,
'tipo' => $dados->tipo,
'padrao' => $dados->padrao,
];
$this->db->update($this->tabela, $conta, $where);
return $this->db->affected_rows();
}
Queries:
INSERT INTO 'tb_conta' ('nome', 'tipo', 'padrao') VALUES ('Teste', '1', 1)
UPDATE 'tb_conta' SET 'nome' = 'Caixa Interno', 'tipo' = '1', 'padrao' = 1 WHERE 'id' = '1'