0

I am adding the barcode with product SKU and product ID in a table using below code:-

File Path: /app/code/[NameSpace]/[ModuleName]/Model/ResourceModel/Custom.php

public function generateBarcodes($object, $attribute, $barcode, $_product)
    {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $barcodeModel = $objectManager->create('Vendor\Module\Model\Barcode');

        $data = array(
            'barcode' => $barcode,
            'product_id' => $_product->getId(),
            'qty' => 1,
            'product_sku' => $_product->getSku(),
            'supplier_code' => '',
            'history_id' => 0000
        );      

        $barcodeModel->setData($data);
        $barcodeModel->save(); 
    }

but I want to stop duplicate record in table, Please let me know how to achieve this in above code.

My table structure:- enter image description here

1

Use the load method for checking, like:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$barcodeModel = $objectManager->create('Vendor\Module\Model\Barcode');
$barcodeModel->load($barcode, 'barcode');
if (!$barcodeModel->getId()) {
    $data = array(
        'barcode' => $barcode,
        'product_id' => $_product->getId(),
        'qty' => 1,
        'product_sku' => $_product->getSku(),
        'supplier_code' => '',
        'history_id' => 0000
    );

    $barcodeModel->setData($data);
    $barcodeModel->save();
}

You can modify the following code by using what you want to check against:

$barcodeModel->load($barcode, 'barcode');

Note: use repository for CRUD operation.

Warning: Don't use object manage, use DI instead

Your Answer

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

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