examples:builder:hasmany_relation

This is an old revision of the document!


Back to Start Page

The hasMany relation

With the hasMany relation a record from a parent table can be linked to one or more record of a child table. No changes in the parent table are required. The key(s) to link parent record to child record(s) are stored in the child table.

Todo Cheat Sheet

  • Required: a parent table and a child table
  • Add a field named: [parentModelName]_id to the child table
  • Create a model for the child table with list and form
  • Extend the parent controller with relation behaviour
  • Extend the parent model with the desired relation definition (hasMany)
  • Define the details of how to handle the relation in the config_relation.yaml in the parent controller
  • Use a Partial widget to include the child fields/forms into the parent form

In the library example used in this wiki, the parent will be the book table, the child table is a review table where a book may have several reviews. Each review is stored in a different record and is linked via the record id of the book (stored in the review records) to a book.

Prerequisites are

  • an installed builder plugin
  • any source code editor or e.g. the Developer Tools plugin with built-in Code editor like to be seen on the screenshoots

Required skills

  • how to work with builder
  • how to create a plugin with builder
  • how to create tables and forms with builder

Preparations

  • a parent table to embed a relation to a child table
  • a child table for the additional field(s) to embed into the parent table
  • In the library example the parent table is books (plural).
  • According to this, the parent model is called book (singular).
  • The related child table shall be named reviews and the respective model is named review.

For a hasMany relation the child table requires a field named by the parent model trailed by '_id'. So in this example the required field has to be called 'book_id'.
In this field the id of the record of the parent table will be stored. So the field has to be of the same type as the parent id field (integer in this example)