除了接受的答案外,最好使用存储库而不是不建议使用的保存方法。在跟踪创建之后还添加了客户通知。
/** @var Magento\Sales\Model\Order\ShipmentRepository */
protected $_shipmentRepository;
/** @var Magento\Shipping\Model\ShipmentNotifier */
protected $_shipmentNotifier;
/** @var Magento\Sales\Model\Order\Shipment\TrackFactory */
protected $_trackFactory; //missing ;
public function __construct(
\Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier,
\Magento\Sales\Model\Order\ShipmentRepository $shipmentRepository,
\Magento\Sales\Model\Order\Shipment\TrackFactory $trackFactory)
{
$this->_shipmentNotifier = $shipmentNotifier;
$this->_shipmentRepository = $shipmentRepository;
$this->_trackFactory = $trackFactory;
}
public function addTrack($shipment, $carrierCode, $description, $trackingNumber)
{
/** Creating Tracking */
/** @var Track $track */
$track = $this->_trackFactory->create();
$track->setCarrierCode($carrierCode);
$track->setDescription($description);
$track->setTrackNumber($trackingNumber);
$shipment->addTrack($track);
$this->_shipmentRepository->save($shipment);
/* Notify the customer*/
$this->_shipmentNotifier->notify($shipment);
}
其中$ shipment是装运对象。通知将通知(发送电子邮件)给用户,并将历史记录项添加到订单状态历史记录集合中。