Set database relation

One of the most common database scenario is when a field is related with another table. For example a product_id that is related with a table products. As in real life this is not enough we also need to specify a title or a name for the related database. So basically there are 3 fields that we need to add:

  1. The fieldName of the basic table (for example the field name product_id)
  2. The table name of the relation (for example products)
  3. The related table title or name (for example the field name product_name)

You can find more about setting a relation from the documentation of setRelation.

Now as you probably mentioned, we didn't add any primary key of the related table and this is because Grocery CRUD is doing it automatically for you. If you need to add a different primary key you should use the setPrimaryKey function as well.

Example

You can see a full working example below:

$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');

$output = $crud->render();

The above code will have as a result the below CRUD: