Mysql trigger return bad stocks value

試著忘記壹切 提交于 2019-12-25 09:17:33

问题


I need help with my trigger. I have two tables 'product' and 'storage'. The idea is when I run update on column 'flag' in table 'storage' trigger must calculate stock for right ID, but always return the wrong value for all product, please see attach. Right stock value should be for 'Test' 10 pcs and for 'aaaaaa' 5 pcs. Thanks for help.

products table:

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `subcategory_id` int(11) NOT NULL,
  `product_name` varchar(255) COLLATE utf8_bin NOT NULL,
  `product_description` varchar(255) COLLATE utf8_bin NOT NULL,
  `product_price` int(11) NOT NULL,
  `product_type` varchar(1) COLLATE utf8_bin NOT NULL,
  `product_quantity` int(11) NOT NULL
) ENGINE=InnoDB;

INSERT INTO `products` (`id`, `subcategory_id`, `product_name`, `product_description`, `product_price`, `product_type`, `product_quantity`) VALUES
(45, 11, 'Test', 'test', 1111, 'G', 15),
(46, 11, 'aaaaaa', 'aaaaaa', 12, 'G', 15);

storage table:

CREATE TABLE `storage` (
  `id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `flag` varchar(1) COLLATE utf8_bin NOT NULL DEFAULT 'A'
) ENGINE=InnoDB;

INSERT INTO `storage` (`id`, `product_id`, `flag`) VALUES
(46, 45, 'A'),
(47, 45, 'A'),
(48, 45, 'A'),
(49, 45, 'A'),
(50, 45, 'A'),
(51, 45, 'A'),
(52, 45, 'A'),
(53, 45, 'A'),
(54, 45, 'A'),
(55, 45, 'A'),
(56, 46, 'A'),
(57, 46, 'A'),
(58, 46, 'A'),
(59, 46, 'A'),
(60, 46, 'A');

mysql trigger:

DELIMITER $$
CREATE TRIGGER `tg_ai_table22` AFTER UPDATE ON `storage` FOR EACH ROW UPDATE products
   SET products.product_quantity = (SELECT COUNT(product_quantity)
FROM STORAGE, (SELECT id FROM products) as prod
WHERE prod.id = storage.product_id AND storage.flag = 'A' LIMIT 1)
$$
DELIMITER ;

PHP Function: Cart controller:

public function addToCart()
    {
        $id = $this->uri->segment(3);
        $data = $this->ProductModel->selectProductToCart($id);
        $cartData = array();
        foreach ($data as $datas) {
            $cartData = array(
                'id' => $datas->id,
                'qty' => 1,
                'price' => $datas->product_price,
                'name' => $datas->product_name
            );
        }
        $this->cart->insert($cartData) ? $this->db->limit(1)->set('flag', 'C')->where('product_id', $cartData['id'])->where('flag', 'A')->update('storage') : '';
    }

public function updateCart()
    {
        $updatedCartData = $this->input->post();

        for ($i = 1; $i <= sizeof($this->cart->contents()); $i++)
        {
            if ($this->cart->contents()[$updatedCartData[$i]['rowid']]['rowid'] == $updatedCartData[$i]['rowid'])
            {
                if ($this->cart->contents()[$updatedCartData[$i]['rowid']]['qty'] > $updatedCartData[$i]['qty'])
                {
                    $result = $this->cart->contents()[$updatedCartData[$i]['rowid']]['qty'] - $updatedCartData[$i]['qty'];
                    for ($j = 1; $j <= $result; $j++)
                    {
                        $this->db->limit(1)->set('flag', 'A')->where('product_id',
                            $this->cart->contents()[$updatedCartData[$i]['rowid']]['id'])->where('flag',
                            'C')->update('storage');
                    }
                } else
                {
                    $result = $updatedCartData[$i]['qty'] - $this->cart->contents()[$updatedCartData[$i]['rowid']]['qty'];
                    for ($j = 1; $j <= $result; $j++)
                    {
                        $this->db->limit(1)->set('flag', 'C')->where('product_id',
                            $this->cart->contents()[$updatedCartData[$i]['rowid']]['id'])->where('flag',
                            'A')->update('storage');
                    }
                }
            }
        }

        $this->cart->update($updatedCartData);
        $this->session->set_flashdata('category_success', 'Kosik bol aktualizovany.');
        redirect('Cart');
    }

ProductController:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('ProductModel');
    }

    public function index($id)
    {
        $data['product'] = $this->ProductModel->selectProduct($id);
        $this->load->view('HeaderView');
        $this->load->view('UpperMenuView');
        $this->load->view('LeftMenuView');
        $this->load->view('ProductView', $data);
        $this->load->view('FooterView');
    }
}

ProductModel:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class ProductModel extends CI_Model
{
    private $table = 'products';

    public function __construct()
    {
        parent::__construct();
    }

    function selectProduct($id)
    {
        return $this->db->get_where($this->table, array('subcategory_id' => $id))->result();
    }

    function selectProductToCart($id)
    {
        return $this->db->get_where($this->table, array('id' => $id))->result();
    }

    public function insertProduct($data)
    {
        $this->db->insert($this->table, $data);
    }

    public function insertProductToStorage($data)
    {
        $this->db->insert('storage', $data);
    }
}

ProductView:

<div class="col-md-9">
    <?php $this->load->view('FlashMessagesView'); ?>
    <ul class="list-unstyled" id="products" data-role="list">
        <?php foreach ($product as $value): ?>
            <li class="span3 col-md-3">
                <div class="thumbnail">
                    <a href="product_details.html"><img src="<?php echo base_url('assets/img/12.jpg'); ?>"/></a>
                    <div class="caption" style="height: 300px; overflow: hidden">
                        <h5><?php echo $value->product_name; ?></h5>
                        <p><?php echo $value->product_description; ?></p>
                    </div>
                    <div class="product_footer caption">
                        <?php if ($value->product_quantity == 0) { ?>
                            <p style="text-align: center"><span style="color:orange"><b>Ordered on request.</b></span></p>
                        <?php } else { ?>
                            <p style="text-align: center">
                                <span style="color:green">
                                    <b>In stock <?php echo $value->product_quantity ?> pcs.</b>
                                </span>
                            </p>
                        <?php } ?>
                        <h4>
                            <a type="button" href="<?php echo base_url('Cart') ?>" id="<?php echo $value->id ?>"
                               class="btn btn-success">Buy</a>
                            <span class="pull-right"><?php echo $value->product_price; ?> &euro;</span>
                        </h4>
                    </div>
                </div>
            </li>
        <?php endforeach; ?>
    </ul>
</div>

回答1:


Your trigger is wrong written, it is make update for all products regardless of id.

To make the changes just for the product with the updated flag change the update statement in the trigger to the following:

UPDATE products
SET products.product_quantity = 
    (   
        SELECT COUNT(product_quantity)
        FROM STORAGE, (SELECT id FROM products) as prod
        WHERE prod.id = storage.product_id 
        AND storage.flag = 'A' LIMIT 1
    )
where id = new.product_id

What we do is adding where id = new.product_id to make update just for updated product flag.

And, i think the way you update the stock is not optimal, why every time you make update, you re calculate the stock?



来源:https://stackoverflow.com/questions/40762200/mysql-trigger-return-bad-stocks-value

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