简体   繁体   English

在Drupal 8中按节点获取分类术语ID

[英]Get Taxonomy Term ID by Node in Drupal 8

I'm trying to get Taxonomy data by particular node. 我正在尝试通过特定节点获取分类法数据。

How can I get Taxonomy Term Id by using Node object ? 如何通过使用Node对象获取Taxonomy Term Id?

Drupal ver. Drupal ver。 8.3.6 8.3.6

If you want to get Taxonomy Term data you can use this code: 如果您想获得Taxonomy Term数据,可以使用以下代码:

$node->get('field_yourfield')->referencedEntities();

Hope it will be useful for you. 希望它对你有用。

PS: If you need just Term's id you can use this: PS:如果您只需要Term的ID,您可以使用:

$node->get('field_yourfield')->getValue();

You will get something like this: 你会得到这样的东西:

[0 => ['target_id' => 23], 1 => ['target_id'] => 25]

In example my field has 2 referenced taxonomy terms. 在示例中,我的字段有2个引用的分类术语。 Thanks! 谢谢!

You could do something like that: 你可以这样做:

$termId = $node->get('field_yourfield')->target_id;

Then you can load the term with 然后你可以加载术语

Term::load($termId);

Hope this helps. 希望这可以帮助。

@Kevin Wenger's comment helped me. @Kevin Wenger的评论帮助了我。 I'm totally basing this answer on his comment. 我的回答完全基于他的评论。

In your code, when you have access to a fully loaded \\Drupal\\node\\Entity\\Node you can access all the (deeply) nested properties. 在您的代码中,当您有权访问完全加载的\\ Drupal \\ node \\ Entity \\ Node时,您可以访问所有(深层)嵌套属性。

In this example, I've got a node which has a taxonomy term field "field_site". 在这个例子中,我有一个节点,它有一个分类术语字段“field_site”。 The "field_site" term itself has a plain text field "field_site_url_base". “field_site”术语本身具有纯文本字段“field_site_url_base”。 In order to get the value of the "field_site_url_base", I can use the following: 为了获得“field_site_url_base”的值,我可以使用以下内容:

$site_base_url = $node->get('field_site')->entity->field_site_url_base->value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM