数据库的用法

5.61K 浏览教程资料

数据库的用法

有大佬给给一个数据库操作的具体用法嘛?

数据库的增删改查,比如 getSelect()的用法等等

0

数据库的增删改查都是用的m2的模型orm,对表实例化模型后,直接调用模型的方法就行。

以test表为例,假设你已经对这个表建了模型

1,根据主键id获取一条记录

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$id = 1;
$testModel = $objectManager->create('Zou\Demo\Model\Test')->load($id);
print_r($testModel->getData());//打印数据

2,查询某个表的数据集

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$testCollection = $objectManager->create('Zou\Demo\Model\ResourceModel\Test\Collection');
//查询某个字段
$testCollection->addAttributeToSelect('status');
//过滤where。比如获取status为1的数据
$testCollection->addAttributeToFilter('status',array('eq'=>1));
//再foreach输出就行
foreach ($testCollection as $_test) {
  print_r($_test->getData());//打印数据
}

3,得到原始的sql

echo $testCollection->getSelect();

4,filter常用的过滤条件

//等于 Equals: eq
$testCollection->addAttributeToFilter('status', array('eq' => 1));
 
//不等于 Not Equals - neq
$testCollection->addAttributeToFilter('sku', array('neq' => 'test-product'));
 
//Like - like
$testCollection->addAttributeToFilter('sku', array('like' => 'UX%'));
 
//Not Like - nlike
$testCollection->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));
 
//In - in
$testCollection->addAttributeToFilter('id', array('in' => array(1,4,98)));
 
//Not In - nin
$testCollection->addAttributeToFilter('id', array('nin' => array(1,4,98)));
 
//NULL - null
$testCollection->addAttributeToFilter('description', 'null');
 
//Not NULL - notnull
$testCollection->addAttributeToFilter('description', 'notnull');
 
//大于 Greater Than - gt
$testCollection->addAttributeToFilter('id', array('gt' => 5));
 
//小于 Less Than - lt
$testCollection->addAttributeToFilter('id', array('lt' => 5));
 
//大于等于 Greater Than or Equals To- gteq
$testCollection->addAttributeToFilter('id', array('gteq' => 5));
 
//小于等于 Less Than or Equals To - lteq
$testCollection->addAttributeToFilter('id', array('lteq' => 5));

参考:

https://www.cnblogs.com/zhengyanbin2016/p/5606917.html

5,删除数据

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$id = 1;
$testModel = $objectManager->create('Zou\Demo\Model\Test')->load($id);
$testModel->delete();

6,更新数据

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$id = 1;
$testModel = $objectManager->create('Zou\Demo\Model\Test')->load($id);
$testModel->setStatus(0);
$testModel->save();
编辑回答
1