Using MySQL triggers to update customers balance

ⅰ亾dé卋堺 提交于 2020-05-23 05:27:15

问题


I need some help in understanding triggers and how they work. I have 3 tables:

Customers
Id | Balance

Invoices
Id | Custid | Amount

Payments
Id | CustId | Amount

I have an insert statement to insert the invoices:

$this->db->insert('invoices', array(
            'CustomerId' => $data['customerId'],
            'Description' => $data['Description'],
            'DateCreated' => $data['DateCreated'],
            'Amount' => $data['Amount']
        ));

and need to update the customers balance after the insert. Similarly, after inserting or creating a payment. I need to deduct from the clients balance.

public function createPayment($data) {
        $this->db->insert('payments', array(
            'CustomerId' => $data['customerid'],
            'DateCreated' => date("Y-m-d H:i:s"),
            'Amount' => $data['amount']
        ));
    } 

Any assistance would be appreciated in creating these triggers.


回答1:


You'll need two triggers - one for the invoice table:

delimiter //
CREATE TRIGGER add_invoice_to_balance AFTER INSERT ON invoices
FOR EACH
ROW
BEGIN
    UPDATE Customers SET balance = balance + NEW.Amount
      WHERE Customers.id = NEW.custid;
END;
//
delimiter;

And one for the payment table:

delimiter //
CREATE TRIGGER add_payment_to_balance AFTER INSERT ON payments
FOR EACH
ROW
BEGIN
    UPDATE Customers SET balance = balance - NEW.Amount
      WHERE Customers.id = NEW.custid;
END;
//
delimiter ;

fiddle here



来源:https://stackoverflow.com/questions/29979057/using-mysql-triggers-to-update-customers-balance

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!