简体   繁体   中英

Codeigniter active record where clause with values from two fields

Am stuck trying to implement simple where clause in codeigniter. What I have is this

public function get_low_stock()
        {
            $this->db->select('*');
            $this->db->where('productQty <=' , '10'); //line where the problem is
            $this->db->from('products');
            $query = $this->db->get();
            return $query->result();
        }

I need the value '10' to be picked from the minQty colum, but have no way to implement this. Such that once I change the minQty in the database, automatically I get the correct low qty. Please see my table structure.

CREATE TABLE IF NOT EXISTS `products` (
`productid` int(11) NOT NULL,
  `productname` varchar(30) NOT NULL,
  `catid` int(11) NOT NULL,
  `productqty` int(11) NOT NULL,
  `buyprice` int(11) NOT NULL,
  `saleprice` int(11) NOT NULL,
  `minqty` int(11) NOT NULL,
  `maxqty` int(11) NOT NULL,
  `alertlevel` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`productid`, `productname`, `catid`, `productqty`, `buyprice`, `saleprice`, `minqty`, `maxqty`, `alertlevel`) VALUES
(1, '2.6 china touch', 1, 9, 2500, 5000, 10, 100, 15),
(4, '2.9 china touch', 1, 10, 2500, 5000, 10, 100, 15),
(5, '3.0 small cable', 1, 5, 2500, 5000, 10, 100, 15);

Try this:

$where = '(productQty <= minqty)';

$this->db->where($where);

as you mentioned minqty is dynamic in your code

$this->db->where('productQty <= minqty');

You can do this two way.

1#

$query=$this->db->query('SELECT * FROM `products` where productqty <= minqty');
return $query->result();

2#

$this->db->select('*');        
$this->db->where('productqty <=minqty',null,false);
//or use this way
//$this->db->where('productqty <=minqty');
$this->db->from('products');
$query = $this->db->get();
return $query->result();

Note You used productQty but your database column name is productqty .It may work.But use the right one.

如果同时查看两个答案,您会发现您的答案完全相同,只是略有不同

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM