magento 2中获取数据库连接

如果没有Mage类,开发人员如何实例化模型或magento-singleton对象?该
Mage :: getModel
Mage :: getSingleton方法已经退役,并在他们的地方Magento的有一个新的“对象管理器”的对象。

现在,此对象管理器是一个PHP单例,您可以通过以下调用进行抓取。

$ object_manager = MagentoCoreModelObjectManager :: getInstance();

Magento正在迈向一种体系结构,该对象将在适当的位置作为_objectManager属性自动可用。

$ this-> _ objectManager
protected $_resource;
public function __construct(
   ...
   \Magento\Framework\App\ResourceConnection $resource
   ...
   ) {
   $this->_resource = $resource;
}

$connection = $this->_resource->getConnection();

或者

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('employee'); //gives table name with prefix

从表中选择数据

$sql = "Select * FROM " . $tableName;
$result = $connection->fetchAll($sql); // gives associated array, table fields as key in array.

从表中删除数据

$sql = "Delete FROM " . $tableName." Where emp_id = 10";
$connection->query($sql);

将数据插入表

$sql = "Insert Into " . $tableName . " (emp_id, emp_name, emp_code, emp_salary) Values ('','XYZ','ABD20','50000')";
$connection->query($sql);

将数据更新到表中

$sql = "Update " . $tableName . "Set emp_salary = 20000 where emp_id = 12";
$connection->query($sql);
赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

版权属于: sbboke版权所有。

转载时必须以链接形式注明作者和原始出处及本声明。

张贴在magento2教程标签:

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论