setPrimaryKey

setPrimaryKey(string $primaryKey, string $tableName)

Set a custom primary key for a table. The common usage for this function is:

  1. When you need to change the default value of a primary key (e.g. to point to a different field for a join)
  2. To optimize your queries and to not have an extra query just for the primary key

For example, let's say that we have the below tables orders and products below:

`orders` (
  `id`,
  `user_id`,
  `product_reference_id`,
  `order_date`
)
`products` (
  `id`,
  `reference_id`,
  `name`,
  `description`
)

These two tables has the id as a PRIMARY KEY. As you can guess though from the tables, the orders table is linked with products table by the reference_id and not by the product it. In that case if you use the setRelation with the above line of code:

$crud->setRelation('product_reference_id', 'products', 'name');

This will join by default with the products.id rather than the products.reference_id as by default the primary key of the products table is the id. In that case in order to achieve the expected behaviour, you should write the extra line:

$crud->setPrimaryKey('reference_id', 'products');
$crud->setRelation('product_reference_id', 'products', 'name');