Chỉ cần làm rõ câu trả lời của Jaimin:
Điều này sẽ làm việc cho bất kỳ thực thể.
Đây không phải là sự thật. Nó sẽ chỉ hoạt động cho các thực thể EAV mở rộngMagento\Eav\Model\Entity\AbstractEntity
Nếu bạn đang làm việc với một thực thể không phải EAV nơi mô hình tài nguyên mở rộng, Magento\Framework\Model\ResourceModel\Db\AbstractDb
bạn sẽ phải triển khai saveAttribute
phương thức trong mô hình tài nguyên của mình.
Trong Magento 2, họ đã thực hiện nó cho Magento\Sales\Model\ResourceModel\Attribute
lớp:
public function saveAttribute(AbstractModel $object, $attribute)
{
if ($attribute instanceof AbstractAttribute) {
$attributes = $attribute->getAttributeCode();
} elseif (is_string($attribute)) {
$attributes = [$attribute];
} else {
$attributes = $attribute;
}
if (is_array($attributes) && !empty($attributes)) {
$this->getConnection()->beginTransaction();
$data = array_intersect_key($object->getData(), array_flip($attributes));
try {
$this->_beforeSaveAttribute($object, $attributes);
if ($object->getId() && !empty($data)) {
$this->getConnection()->update(
$object->getResource()->getMainTable(),
$data,
[$object->getResource()->getIdFieldName() . '= ?' => (int)$object->getId()]
);
$object->addData($data);
}
$this->_afterSaveAttribute($object, $attributes);
$this->getConnection()->commit();
} catch (\Exception $e) {
$this->getConnection()->rollBack();
throw $e;
}
}
return $this;
}