Answers:
是的,您可以在Magento中运行直接SQL查询,最好的方法是使用读写资源。您可以使用以下方法来满足需要:
$ resource =法师:: getSingleton('core / resource'); $ readConnection = $ resource-> getConnection('core_read'); $ writeConnection = $ resource-> getConnection('core_write');
要运行选择,您可以执行以下操作:
$ readConnection = $ resource-> getConnection('core_read'); $ query ='选择* FROM'。$ resource-> getTableName('catalog / product'); $ results = $ readConnection-> fetchAll($ query); / *获得结果* / var_dump($ results);
要将某些内容写入数据库,请使用:
$ resource =法师:: getSingleton('core / resource'); $ writeConnection = $ resource-> getConnection('core_write'); $ table = $ resource-> getTableName('catalog / product'); $ query =“ UPDATE {$ table} SET {item} ='{value}'WHERE entity_id ='value'”; $ writeConnection-> query($ query);
希望这对您有所帮助。
有一种更合适的方法可以避免SQL注入。
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('your/model');
您可以创建:
$write->insert(
$table,
['column_1' => 1, 'column_2' => 2]
);
读:
$select = $write->select()
->from(['tbl' => $table], ['entity_id', 'company'])
->join(['tbl2' => $table2], 'tbl.entity_id = tbl2.product_id', ['stuff'])
->where('name LIKE ?', "%{$name}%")
->group('company');
$results = $write->fetchAll($select);
更新:
$write->update(
$table,
['column_1' => 3, 'column_2' => 4],
['entity_id = ?' => 123]
);
删除:
$write->delete(
$table,
['entity_id IN (?)' => [123, 456]]
);
插入多个:
$rows = [
['col_1'=>'value1', 'col_2'=>'value2', 'col_3'=>'value3'],
['col_1'=>'value3', 'col_2'=>'value4', 'col_3'=>'value5'],
];
$write->insertMultiple($table, $rows);
插入重复更新:
$data = [];
$data[] = [
'sku' => $sku,
'name' => $name
];
$write->insertOnDuplicate(
$table,
$data, // Could also be an array of rows like insertMultiple
['name'] // this is the fields that will be updated in case of duplication
);