Magento 2 Custom Table – Get Data from Custom Table by Entity_ID

magento2

Table custom like this

enter image description here

I want get data from table " custom " by id in block magento 2. Please help me! Thanks all

UPDATE

I want get data by " custom_id "

enter image description here

UPDATE

function __construct

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Webkul\MpSellerMapLocator\Model\Mpsellermaplocator $mpSellerMapLocatorModel,
    array $data = []
) {
    parent::__construct($context, $data);
    $this->mpSellerMapLocatorModel = $mpSellerMapLocatorModel;
}

get data

$customId = 4;
$marketplaceMpsellermaplocator = $this->mpSellerMapLocatorModel->addFieldToFilter('custom_id', $customId);
echo "<pre>";var_dump($marketplaceMpsellermaplocator->getData());
exit;

Best Answer

Use load by Id to get data by id.

Try with below way.

Add below code in your block file.

<?php
namespace Test\Module\Block;

class TestBlock extends \Magento\Framework\View\Element\Template
{

  protected $customTable;  


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Namespace\ModuleName\Model\customTableFactory $customTable

    ) {


        $this->customTable = $customTable;
        parent::__construct($context);
    }
    public function getLoadProduct($id)
    {
        return $this->customTable->create()->load($id);
    }

}

In the above code, I inject class \Namespace\ModuleName\Model\customTableFactory in your case you have to inject your model class. and pass your entity_id in $id

That's it! I hope it helps.


Update:

You can also get data by another field like below.

protected $customTablecollection;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Webkul\MpSellerMapLocator\Model\ResourceModel\Mpsellermaplocator\collection $mpSellerMapLocatorModel,
    array $data = []
) {
    parent::__construct($context, $data);
    $this->mpSellerMapLocatorModel = $mpSellerMapLocatorModel;
}

And then you can use your variable directly in your code:

$customId = 4;
$marketplaceMpsellermaplocator = $this->mpSellerMapLocatorModel->addFieldToFilter('custom_id', $customId);
echo "<pre>";var_dump($marketplaceMpsellermaplocator->getData());
exit;
Related Topic