Create an EAV Model in Magento2.

Create an EAV Model in Magento2 in simple way.

Employee entity,as per requirements,is modeled as an EAV model.

First create an EAV model class,have to define under the app/code/Skynet/Office/Model/Employee.php file as follows:

namespace Skynet\Office\Model;


use Magento\Framework\Model\AbstractModel;

class Employee extends AbstractModel
{
const ENTITY = 'skynet_office_employee';
public function __construct()
{
    $this->_init('Skynet\Office\Model\ResourceModel\Employee');
}
}

Extending from the Magento\Framework\Model\AbstractModel class,which is the same as with the simple model previously described.

Next,we create an EAV model resource class,defined under under the app/code/Skynet/Office/Model/ResourceModel/Employee.php file as follows:

namespace Skynet\Office\Model\ResourceModel;


class Employee extends \Magento\Eav\Model\Entity\AbstractEntity
{
 public function __construct()
 {
     $this->_read = 'skynet_office_employee_read';
     $this->_read = 'skynet_office_employee_write';
 }
 public function getEntityType()
 {
     if(empty($this->_type)){
         $this->setType(\Skynet\Office\Model\Employee::ENTITY);
     }
     return parent :: getEntityType();
 }
}

Our resource class extends from \Magento\Eav\Model\Entity\AbstractEntity,

and sets the $this->_read,$this->_read class properties through _construct.The read and write connections need to be named or else Magento produces an error when using our entities.The getEntityType method internally sets the _type value to \Skynet\Office\Model\Employee::ENTITY,which is the string skynet_office_employee.

Finally,we create our collection class,defined under the app/code/Skynet/Office/Model/ResourceModel/Employee/Collection.php file as follows:

namespace Skynet\Office\Model\ResourceModel\Employee;


class Collection extends \Magento\Eav\Model\Entity\Collection\AbstractCollection
{
 public function __construct(){
     $this->_init('Skynet\Office\Model\Employee',
         Skynet\Office\Model\ResourceModel\Employee);
 }
}addAttributeToFilter

The collection class extends from \Magento\Eav\Model\Entity\Collection\AbstractCollection and,similar to the model class,does a $this->_init method call within __construct._init accepts two parameters:full model class name

Skynet\Office\Model\Employee,and the full resource class name Skynet\Office\Model\ResourceModel\Employee.

AbstractCollection has the same parents tree as the simple model collection class,but on its own it implements a lots of EAV collection specific method like addAttributeToFilter,addAttributeToSelect,
addAttributeToSort,and so on.

Total Page Visits: 7676 - Today Page Visits: 1

Leave a Reply