Only one line as true, MYSQL - Codeigniter

Asked

Viewed 54 times

0

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 that regardless of the amount of lines recorded in this table, there is only one result in the field padrao, the value of which is equal to true

Both in new insert, and in the update.

Setting: If entering a new record and the value of the field padrao be equal to true, then automatically all other values already recorded 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();
}

darlings:

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'

2 answers

1


I decided to create a new function and put a condition in the functions:

function created

// mark_all_false
public function mark_all_false()
{
    $this->db->where('padrao', true)->update($this->tabela, array('padrao' => false));
}

Created condition

if ($dados->padrao == true)
{
    $this->mark_all_false();
}

0

Create a Trigger to act before select to update all that are true so when insert the new it will come as TRUE.

CREATE TRIGGER BEFORE INSERT ON Tb_account FOR EACH ROW BEGIN UPDATE tb_account SET default = false WHERE default = true; END$

  • 1

    I did not understand how to apply in the amending function

  • This command will run you straight into your database, and will not leave you in the code,

  • Oh yes, I understood, I also saw another way to do directly in the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.