Score:2

How can I specify the relation type between two entities?

ye flag

I am new two Drupal

Trying to create two entities, Post and Category (This is for tests purposes)

A Post can have one Category, and a Category can have multiple Post

Here is my implementation of the field category_id on the Post entity:

  $fields['category_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Category'))
  ->setDescription(t('The Name of the associated category.'))
  ->setSetting('target_type', 'test_category')
  ->setSetting('handler', 'default');

My questions are:

  1. is There a way to define the type of relationship (hasOne in this case)
  2. What is the purpose of the handler? if someone can point me to a documentation explaining what we can do with a handler in this kind of situations.
  3. On Category entity, Should I reference the Post entity to get posts of a category for example.

I am using Drupal 9.3, I've a Symfony backgroud

leymannx avatar
ne flag
You should probably use taxonomy terms for the categories. It's already built-in that every term page then shows all content associated with it.
beta-developper avatar
ye flag
I totally agree. A I said am new to Drupal and I am trying to understand the core concepts.
leymannx avatar
ne flag
I see. You can maybe imagine it as database query "get all posts that have X category selected". For that you don't need to have the posts stored in the category. One way is enough to later have the correct result both ways.
Score:3
cn flag
  1. No, entity references are not synonymous with DB relationships; in my experience it rarely helps to think about them as such.

  2. It's the entity selection handler; the plugin which manages which entities are available to be added to the field instance. See https://www.axelerant.com/blog/writing-entity-reference-selection-plugin for an example.

  3. You could, but there might not be any point - the fields won't know about each other or interact with each other, so you'd end up having to manage to separate fields for the same relationship, which is just awkward. Views does have a reverse entity reference relationship feature, so depending on requirements the functionality you need might already be there.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.