How to create ER diagram in MermaidJS

1. Install MermaidJS

You can install MermaidJS by including the MermaidJS library in your project or by installing it via npm.

npm i mermaid

2. Define the diagram

To create an ER diagram, start the definition with erDiagram. Connect entities with a relationship line using crow's-foot cardinality markers on each side, then optionally list each entity's attributes inside curly braces.

erDiagram
    CUSTOMER ||--o{ ORDER : places
    ORDER ||--|{ LINE_ITEM : contains
    CUSTOMER {
        string name
        string email
    }
    ORDER {
        int orderId
        date orderDate
    }
    LINE_ITEM {
        int quantity
        float price
    }

In this example, one CUSTOMER places zero or more ORDERs, and each ORDER contains one or more LINE_ITEMs.

3. Cardinality notation

The crow's-foot symbols on each end of a relationship line describe how many rows on that side can participate in the relationship:

CardinalitySyntaxMeaningPreview
Exactly oneA ||--|| BExactly one row on this side (double bar)
Zero or oneA |o--o| BZero or one row on this side (bar + circle)
Zero or moreA }o--o{ BZero, one, or many rows on this side (crow's foot + circle)
One or moreA }|--|{ BAt least one, possibly many rows on this side (crow's foot + bar)

4. Attributes and relationship labels

List each entity's attributes as type name pairs inside curly braces, as shown for CUSTOMER, ORDER, and LINE_ITEM above. Add an optional : label after a relationship (e.g. places, contains) to describe what the relationship represents.

5. Render the diagram

Once you have defined the diagram, you can render it on your webpage by including the MermaidJS library and calling the mermaid function with the diagram definition as a string. Here is an example of how to do this

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>
      mermaid.initialize({
        startOnLoad: true
      });
    </script>
  </head>
  <body>
    <div class="mermaid">
      erDiagram
        CUSTOMER ||--o{ ORDER : places
        ORDER ||--|{ LINE_ITEM : contains
        CUSTOMER {
          string name
          string email
        }
        ORDER {
          int orderId
          date orderDate
        }
        LINE_ITEM {
          int quantity
          float price
        }
    </div>
  </body>
</html>

You can use this MermaidJS Playground Link to explore that particular example.