0

I am working on the Magento 2 custom model file, my table name is custom_log, then I have created the following model file in my module directory.

Test/Customlog/Model/Log.php

namespace Test\Customlog\Model;
class Log extends \Magento\Framework\Model\AbstractModel {

  protected function _construct() {
      $this->_init('Test\Customlog\Model\ResourceModel\Log');
  }

  public function getPrimeryField($field,$value) {
      $table = $this->getMainTable();
      $connection = $this->getConnection();
      $where = $connection->quoteInto("$field = ?", $value);
      $select = $connection->select()->from($table,array('id'))->where($where);
      $id = $connection->fetchOne($select);
      return $id;
  }

  public function setLogData($values) {
    $id = $this->getPrimeryField('log_type',$value['log_type']);
    if($id) {
      $log =  $this->load($id);
    }
    else {
      $log = $this;
    }
    $log->setData($values)->save();
  }
}

Test\Customlog\Model\ResourceModel\Log.php

namespace Test\Customlog\Model\ResourceModel;
class Log extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{

    public function __construct(
        \Magento\Framework\Model\ResourceModel\Db\Context $context
    )
    {
        parent::__construct($context);
    }

    protected function _construct()
    {
        $this->_init('custom_log', 'id');
    }

}

Test\Customlog\Model\ResourceModel\Log\Collection.php

namespace Test\Customlog\Model\ResourceModel\Log;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * Define model & resource model
     */
    protected function _construct() {
        $this->_init(
            'Test\Customlog\Model\Log',
            'Test\Customlog\Mode\ResourceModel\Log'
        );
    }

}

Then, like to get save or update to the table values instead of using the Factory pattern in a controller file, I just like to call a function inside the model and load the data by the field for an update or else create a new record.

Test/Customelog/Controller/Index/Index.php

Class Index extent ..... {
       protected $_log;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Test\Customlog\Model\Log $log

) {
    $this->_log = $log;
    parent::__construct($context);
}

public function execute() {

  $this->_log()->setLogData($values);
}

}

  • and what is your question? – Philipp Sander Jan 24 at 12:49
  • Question : The above one is not working, it's throwing error in getconnection. the above procedure is valid one or need to do some other way? – senthil Jan 24 at 12:51
  • provide us the error.... – Philipp Sander Jan 24 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.