0

I'm using Magento 2.3.4 , and i kinda confuse with how to use Magento 2 model correctly or follow the code standard. I have a model collection with database structure like this:

brand_id | name | type | manufacturer | priority | created_at | updated_at

I'm using Mage2gen.com to generate model, and got the following files: https://mage2gen.com/load/33e2b596-8220-4434-b852-b55c2c95293a?main_version=3

enter image description here

when i want to add new or get record i do it like this:

public function __construct(
  \Vendor\Module\Model\BrandFactory $brandFactory,
){
  $brandFactory = $this->brandFactory;
}

//add new record to the table
function addNewBrand($data){
  $this->brandFactory->create()->setData($data)->save();
}

//update new record to the table
function updateBrand($data){
  $this->brandFactory->create()->load($data['id'])->setData($data)->save();
}

//get data by name
function getBrandByName($name){
  return $this->brandFactory->create()->getCollection()->addFieldToFilter('name',$name)->getFirstItem();
}

//update data by name
function updateBrandByName($data){
  $model = $this->getBrandByName($data['name']);
  if(!$model->getId()) $model = $this->brandFactory->create();
  $model->setData($data)->save();
}

function getBrands(){
  return $this->brandFactory->create()->getCollection();
}

i always use the model factory to crud the data , but i just read in the documentation that this model is depecrated , what is the Correct way for me to do above functionality ?

1
  • you have the brand repository. Check if it has get/save/delete/getList methods
    – Marius
    Commented May 21, 2020 at 10:43

1 Answer 1

1

You should use repositories instead of factory https://alanstorm.com/magento_2_understanding_object_repositories/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.