3

How do I set up n:m database relation in a custom Drupal 8 module?

I want to create task entities that may be related to different users (a task may have multiple related users and a user may have different tasks). Using the database directly I would create two tables(as the user table already exists), a tasks table and a task_users table which contains the relations (User IDs and Task ID)s. How do provide something like this in Drupal 8?

I only find a way to handle 1:n relations in setting up a user reference field (entity_reference) as a base field definition.

$fields['user'] = BaseFieldDefinition::create('entity_reference')

But how do I provide a relationship table?

1 Answer 1

4

You can set unlimit cardinality, some like this:

->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)

This create a intermediate table to reference two entities.

Check api documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetCardinality/8.6.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.