0

I can get data from database by calling model factory in controller.

class Index extends \Magento\Framework\App\Action\Action{

protected $_entityFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \My\Module\Model\EntityFactory $entityFactory
){
    $this->_entityFactory = $entityFactory;
    return parent::__construct($context);
}

public function execute(){
    $entity = $this->_entityFactory->create();

    // get data where entity_id = 1
    $entity->load(1);

    // get data where entity_name = Rizki
    $entity->load('Rizki', 'entity_name');
}

Now, i want get data with multiple condition. I have tried

$entity->load(['Rizki', 'entity_name'], ['Bandung' => 'address'])

But it gives me error Exception #0 (Exception): Notice: Array to string conversion.

1 Answer 1

2

Class Magento\Framework\Model\AbstractModel:

/**
 * Load object data
 *
 * @param integer $modelId
 * @param null|string $field
 * @return $this
 * @deprecated
 */
public function load($modelId, $field = null)
{
    $this->_beforeLoad($modelId, $field);
    $this->_getResource()->load($this, $modelId, $field);
    $this->_afterLoad();
    $this->setOrigData();
    $this->_hasDataChanges = false;
    $this->updateStoredData();
    return $this;
}

There is no such load method for AbstractModel instance with array parameters. Therefore, to load model using multiple conditions, my favorite method is like this:

$model = $modelFactory
    ->create()
    ->getResource()
    ->getCollection()
    ->addFieldToFilter('[field_name_1]', '[value_1]')
    ->addFieldToFilter('[field_name_2]', '[value_2]')
    ->getFirstItem()
;

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.