Skip to content

Model Class

primaryKey()

primaryKey() — returns string

Available in: model Category: Miscellaneous Functions

Returns the name of the primary key column for the table mapped to a given model. Wheels determines this automatically by introspecting the database. If the table uses a single primary key, the function returns that key’s name as a string. For tables with composite primary keys, the function will return a list of all keys. You can optionally pass in the position argument to retrieve a specific key from a composite set. This function is also available as the alias primaryKeys().

NameTypeRequiredDefaultDescription
positionnumericno0If you are accessing a composite primary key, pass the position of a single key to fetch.
1. Get the primary key of a simple table
// For employees table with id as primary key
keyName = model("employee").primaryKey();
// Returns: "id"

2. Alias usage
keyName = model("employee").primaryKeys();
// Returns: "id"

3. Composite primary key table (e.g., order_products with order_id + product_id)
keys = model("orderProduct").primaryKey();
// Returns: "order_id,product_id"

4. Fetching just the first key in a composite set
firstKey = model("orderProduct").primaryKey(position=1);
// Returns: "order_id"

5. Fetching the second key in a composite set
secondKey = model("orderProduct").primaryKey(position=2);
// Returns: "product_id"