CRUD NO MAGENTO 2 A PARTIR DO ZEND2

De Tek-System Wiki
Revisão de 18h38min de 21 de fevereiro de 2018 por Sergio Mendonça (discussão | contribs)
Ir para navegação Ir para pesquisar

1) Buscando a tabela no banco

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('clientela');

onde clientela é o nome da tabela

2) CRUD

// INSERT DATA
$name = 'Mukesh Chapagain';
$age = 99;
$email = 'mukesh@example.com';
$sql = "INSERT INTO " . $tableName . " (id, name, age, email) VALUES (, '$name', $age, '$email')";
$connection->query($sql);
$sql = "INSERT INTO " . $tableName . " (id, name, age, email) VALUES (, 'Hello World', 88, 'hello@example.com')";
$connection->query($sql);
// SELECT DATA
$sql = "SELECT * FROM " . $tableName;
$result = $connection->fetchAll($sql); 
// UPDATE DATA
$id = 1; // table row id to update
$sql = "UPDATE " . $tableName . " SET name = 'Your Name', email = 'your-email@example.com' WHERE id = " . $id;
$connection->query($sql);
// DELETE DATA
$id = 1; // table row id to delete
$sql = "DELETE FROM " . $tableName . " WHERE id = " . $id;
$connection->query($sql);

3) SELECT COM CONDICAO

$id = 2;
$fields = array('id', 'name');
$sql = $connection->select()
                 ->from($tableName) // to select all fields
                 //->from($tableName, $fields) // to select some particular fields                  
                 ->where('id = ?', $id)
                 ->where('age > ?', 30); // adding WHERE condition with AND
$result = $connection->fetchAll($sql);

4) MELHOR FORMA DE USAR JOIN:

$id_clientela = 1;
$fields = array('id', 'name');
$sql = $connection->select()
                       ->from($tableName) // to select all fields
                       ->joinUsing('telefone_clientela', 'id_clientela')
                       ->where('clientela.id_clientela = ?', $id_clientela);
$result = $connection->fetchAll($sql);