Question

I want to know, what is the correct way to implement CRUD operations in Magento 2?

because I found a lot of examples but they use deprecated methods.

I created a table ('quote reserved item') with some. id (PK) quote_id FK on entity_id form quote table. product_id.

I want to save update and read information from this table. So i created the following classes :

enter image description here

  1. Api\ReservedItemRepositoryInterface.php that has a method save(); Api\Data\ReservedItemInterface.php

    Model\ResourceModel\ReservedItem\Collection.php Model\ResourceModel\ReservedItem.php Model\ReservedItem.php Model\ReservedItemRepository.php here i want to implement that save method without using deprecated methods. If that is not possible which method should i use.

    class ReservedItemRepository implements ReservedItemRepositoryInterface{

    protected $collectionFactory;
    
    protected $reservedItemFactory;
    
    public function __construct(
        CollectionFactory $collectionFactory,
        ReservedItemFactory $reservedItemFactory
    )
    {
        $this->collectionFactory = $collectionFactory;
        $this->reservedItemFactory = $reservedItemFactory;
    }
    
    /**
     * @param ReservedItemInterface $reservedItem
     * @return ReservedItemInterface
     */
    public function save(ReservedItemInterface $reservedItem, $saveOptions = false)
    {
    
    }
    
Was it helpful?

Solution

Make your class look like this:

class ReservedItemRepository implements ReservedItemRepositoryInterface{

    protected $collectionFactory;

    protected $reservedItemFactory;
    protected $reservedItemResourceModel;

    public function __construct(
        CollectionFactory $collectionFactory,
        ReservedItemFactory $reservedItemFactory,
        ReservedItem $reservedItemResourceModel //this should be an instance the ResourceModel\ReserverItem class
    )
    {
        $this->collectionFactory = $collectionFactory;
        $this->reservedItemFactory = $reservedItemFactory;
        $this->reservedItemResourceModel = $reservedItemResourceModel;
    }

    /**
     * @param ReservedItemInterface $reservedItem
     * @return ReservedItemInterface
     */
    public function save(ReservedItemInterface $reservedItem, $saveOptions = false)
    {
        $this->reservedItemResourceModel->save($reservedItem);
    }

OTHER TIPS

You are suppose to instantiate model that maps to the table that you want up update. And use it's setData() method. Once all data is populated. use save() method which will in tern will write values into database.

you could use pestle https://github.com/astorm/pestle

pestle.phar generate_crud_model Yourvendor_Yourmodule Yourmodelname

this will create the model, the resource model, the model repository, table schema(basic one) and the api interface ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top