29.07.2016

Magento 2. Databases and modules.

Working with Magento 2 collections

(We need the module that we created in the previous recipe – Creating a flat table with models)

 

STEP I – Create a Collection controller action:

Create the file:

app/code/Magedd/Education/Controller/Index/Collection.php

STEP II – Load 10 products by collection:

 
(file app/code/Magedd/Education/Controller/Index/Collection.php)

Change  public function execute():

When loading the page /magedd/index/collection, we see a dump of the first 10 products.

When we look at the array, we see no product attributes in the dump.
 

STEP III – Adding an attribute to the product collection:

 
(file app/code/Magedd/Education/Controller/Index/Collection.php)

We have to use ->addAttributeToSelect().

Change  public function execute():

When reloading the page /magedd/index/collection, we will see an array of each product with the three attributes (name, price, image).
 

STEP IV – Adding a filter on the product collection:

 
(file app/code/Magedd/Education/Controller/Index/Collection.php)

We have to use ->addAttributeToFilter().

Change  public function execute():

The code in this statement will create a WHERE name = ‘Overnight Duffle’ statement to the query, so all the items where the name is Overnight Duffle will be returned.

With the addAttributeToFilter() method, we can do more:

 

you can create a WHERE entity_id IN (159, 160, 161):

->addAttributeToFilter(‘entity_id’, array( ‘in’ => array(159, 160, 161) ));

 

query with the WHERE name LIKE ‘%Sport%’:

->addAttributeToFilter(‘name’, array( ‘like’ => ‘%Sport%’ ));

 

When the queries become more complex you can print the SQL query:

 
$productCollection->getSelect()->__toString();

 

STEP V – Update (set) some attributes for all the entities in the collection:

 
(file app/code/Magedd/Education/Controller/Index/Collection.php)

We have to use ->setDataToAll() and then use $productCollection->save();

Change  public function execute():