In case you've missed it, you are looking at an older version of the website. Checkout our latest version, we promise you will love it 😍

set_relation

void set_relation( string $field_name , string  $related_table, string  $related_title_field  [, mixed $where [, string $order_by ] ] )
Quick Description: Set a relation 1-n database relation.

Set a relation 1-n database relation. This will automatically create a dropdown list to the fields and show the actual name of the field and not just a primary key to the list. An example of this:

 
$crud->set_relation('user_id','users','username');
 

You can have as many fields you like to call from the other table and the syntax is really simple. Just at the 3rd field you will have the symbol { and } . So it will be for example:

 
$crud->set_relation('user_id','users','{username} - {last_name} {first_name}');
 

And you can have whatever syntax or symbols you like. So for example you can have:

 
$crud->set_relation('user_id','users','{username} ( {last_name} {first_name} )');
 
The parenthesis is just to show you that you can insert whatever symbol you like.

You can also have a where clause at the 4th parameter (is not a required parameter). For example:

 
$crud->set_relation('user_id','users','username',array('status' => 'active'));
 

It works exactly like codeigniter's where clause (you can add an array or a string), with the only difference that you cannot add a 3rd parameter (for example true or false).

The 5th parameter (not required) is the order_by. For example:

 
$crud->set_relation('user_id','users','username',null,'priority ASC');
 

I added the 4th parameter as null because we don't need a where clause in this example. If we also need a where clause we can simply do:

 
$crud->set_relation('user_id','users','username',array('status' => 'active'),'priority ASC');
 

You can also see a simple working example below:

function employees_management()
{
    $crud = new grocery_CRUD();
 
    $crud->set_theme('datatables');
    $crud->set_table('employees');
    $crud->display_as('officeCode','Office City');
    $crud->set_subject('Employee');
 
    $crud->set_relation('officeCode','offices','city');
 
    $output = $crud->render();
 
    $this->_example_output($output);
}
Note: The below example is an iframe so it might appeared with a scroll bar. If you like you can view the example on a new tab