代码中的注释应该解释一切:
<?php
use Drupal\paragraphs\Entity\Paragraph;
// Create single new paragraph
$paragraph = Paragraph::create([
'type' => 'paragraph_machine_name',
'field_machine_name' => 'Field value',
]);
$paragraph->save();
// Create multiple new paragraphs
$multiParagraph1 = Paragraph::create([
'type' => 'paragraph_machine_name',
'field_machine_name' => 'Field value',
]);
$multiParagraph2 = Paragraph::create([
'type' => 'paragraph_machine_name',
'field_machine_name' => 'Field value',
]);
$multiParagraph1->save();
$multiParagraph2->save();
// Save paragraph to node it belongs to
$newCompanyNode = Node::create([
'type' => 'node_machine_name',
'title' => 'new_node_title',
// Insert a single paragraph
'node_field_paragraph_machine_name' => array(
'target_id' => $paragraph->id(),
'target_revision_id' => $paragraph->getRevisionId(),
),
// Insert multiple paragraphs into the same reference field
'node_paragraph_field_machine_name' => array(
array(
'target_id' => $multiParagraph1->id(),
'target_revision_id' => $multiParagraph1->getRevisionId(),
),
array(
'target_id' => $multiParagraph2->id(),
'target_revision_id' => $multiParagraph2->getRevisionId(),
),
),
]);
// Makes sure this creates a new node
$newCompanyNode->enforceIsNew();
// Saves the node
// Can also be used without enforceIsNew() which will update the node if a $newCompanyNode->id() already exists
$newCompanyNode->save();