M
M
Michael2018-06-15 20:24:09
Magento
Michael, 2018-06-15 20:24:09

How to assign an object id to its collection elements in magento 2?

It is required to create a payment and its items (paid orders). It is not difficult to create separately, but I don’t know how to create it in a transaction.
Code example:

$payment = $this->paymentFactory->create();
$payment->setCustomerId($order->getCustomerId());
$payment->setAmount($amount);
$payment->save();

$paymentOrder = $this->orderConvertor->toPaymentOrder($order);
$paymentOrder->setAmount($amount);
$paymentOrder->setPaymentId($payment->getId()); // <- проблема в этом
$paymentOrder->save();

The transaction class allows you to add and save elements:
$transaction = $this->transactionFactory->create();
$transaction->addObject($payment);
$transaction->save();

I know how to add items to payment and all this in a transaction, but it's not clear how to set the payment_id for an item in the "middle of a transaction".
There is an idea to add the afterSave method and go through the collection and assign this payment_id to each item. For Payment already added a collection for this.
In general, I would like to do how it is done in the magenta itself, I'm sure that this has already been decided, but I don't know where to peep.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2018-06-15
@springimport

Seems to have found it.

namespace Magento\Sales\Model\ResourceModel\Order;

class Payment extends SalesResource
{
    // ...

    protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {
        /**@var $object \Magento\Sales\Model\Order\Payment */
        parent::_beforeSave($object);
        if (!$object->getParentId() && $object->getOrder()) {
            $object->setParentId($object->getOrder()->getId());
        }
        return $this;
    }
}

In the code above, before saving the payment resource model (what an irony), it checks for the presence of "payment_id" and that the ancestor has an id. I think that this is it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question