Drupal Commerce:无法从产品变体对象获取变体类型计算机名称



我通过id成功接收产品变更对象

$variation = Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load(8);
然后我成功地接收到它的结构,如
(
[variation_id] => Array
(
[x-default] => 8
)
[type] => Array
(
[x-default] => router
)
[uuid] => Array
(
[x-default] => a44c2c31-2131-4c99-82a6-856b566d97cf
)
...

byprint_r()like

echo '<pre>';
print_r($variation);
echo '</pre>';

现在如果我尝试通过$variation->sku->value获取SKU,我得到它

但是如果我试图通过$variation->type->value获得变化类型的机器名称,我什么也得不到(gettype($variation->type->value)返回NULL)。

我们仍然可以在结构体中看到它的值router

为什么和如何获得机器名?

很奇怪:print_r()显示的方式是$variation->type->value

但是我已经成功地得到了

$variation->type[0]->target_id

这个答案可能对将来偶然看到这篇文章的人有用

要从Drupal 9 Commerce中的产品变体对象中获取变体类型的机器名,可以使用以下代码:

<?php
use DrupalcommercePurchasableEntityInterface;
// Load the product variation object.
$product_variation = ...;
// Ensure the object is a valid product variation.
if ($product_variation instanceof PurchasableEntityInterface) {
// Get the variation type.
$variation_type = $product_variation->getPurchasedEntity()->bundle();

// Get the variation type machine name.
$variation_type_machine_name = $variation_type->id();

// Use the variation type machine name as needed.
...
} 

此代码使用PurchasableEntityInterface确保加载对象是有效的产品变体。getPurchasedEntity ()方法用于获取表示变量的底层实体,而bundle()方法得到变分类型。然后可以使用id()来获得变化类型的机器名称方法。

最新更新