string $fieldName,
        string $junctionTable,
        string $referrerTable,
        string  $primaryKeyJunctionToCurrent, 
        string $primaryKeyToReferrerTable, 
        string $referrerTitleField
        [, string $sortingFieldName [, array|string $where]]

At relational databases it is very common to have many to many relationship (also known as n:n or m:n). Grocery CRUD is doing it easy for you to connect 3 tables and also use it in your datagrid and forms. The syntax is easy and you just need to add the tables and the relations. All the primary keys are automatically added so you will not need to.

Set Relation N to N tables

For example:

$crud->setRelationNtoN('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname');
$crud->setRelationNtoN('categories', 'film_category', 'category', 'film_id', 'category_id', 'name');


The variable $referrerTitleField can also be written with brackets. With this way you can achieve a result to get more than one fields from the title table or create your own type of title. An example in order to understand it better is as follows:

$crud->setRelationNtoN('actors', 'film_actor', 'actor', 'film_id', 'actor_id', '{reference_id} - {first_name} {last_name}');

The above example will output strings that will take the fields from actor.reference_id, actor.first_name and actor.last_name . The final output will look like this "345 - John Smith", "367 - George Brown",... e.t.c.


Please be aware that the $where variable is only available in grocery CRUD Enterprise.

The where statement will take the exact same format as where function of grocery CRUD Enterprise.

For example a common usage will look like this:

$crud->setRelationNtoN('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname', null, [
     'actor.state' => 'public'

A full working example can be found below:

$crud->setSubject('Film', 'Films');

$crud->setRelationNtoN('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname');
$crud->setRelationNtoN('categories', 'film_category', 'category', 'film_id', 'category_id', 'name');

$output = $crud->render();

The result of the above code is here. As you can see we now have two new fields (actors and categories) with multiple select functionality.