setRelation

setRelation(string $fieldName , string $relatedTable, string $relatedTitleField)

A simple database relation between tables is very common. For example if we would like to set a relation for the below tables:

Set Relation tables

The primary key of the basic table (employees) and the primary key of the relational table (offices) is recognised automatically . So you need to add only three strings.

  1. The field name at our basic table that we need to related with the foreign key (in our example: officeCode)
  2. The relation table (in our example: offices)
  3. The field that it is recognisable as the title of the related table (in our example: city)

For example:

$crud->setRelation('officeCode', 'offices', 'city')

Showing more than one fields

You can also use multiple fields from the relation table by adding brackets ( { and } ) . For example:

$crud->setRelation('officeCode', 'offices', '{city} - {telephone}');

Where statement at the setRelation function

You can also include a 4th parameter at the setRelation function with the same syntax that is used with where function. You can see some examples below:

$crud->setRelation('officeCode', 'offices', 'city', ['is_deleted' => 'no'])

For more about how to use the 4th parameter of where you can also check the full documentation of where method.

Full Example

A full working example can be found here:

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

$output = $crud->render();

You can see the result of the above code at the below datagrid. As you can see there is a dropdown list at the city (we did rename the officeCode as City to be more readable to the end user)

Ooooops, something went wrong! If you can see this message, this is probably a misconfiguration in Grocery CRUD Enterprise!