Skip to content

Model Object

key()

key() — returns string

Available in: model Category: Miscellaneous Functions

Returns the value of the primary key for the object. If you have a single primary key named id, then someObject.key() is functionally equivalent to someObject.id. This method is more useful when you do dynamic programming and don’t know the name of the primary key or when you use composite keys (in which case it’s convenient to use this method to get a list of both key values returned).

NameTypeRequiredDefaultDescription
$persistedbooleannofalse
$returnTickCountWhenNewbooleannofalse
1. Single Primary Key

employee = model("employee").findByKey(42);

<cfoutput>
Employee ID: #employee.key()# <!--- Equivalent to employee.id --->
</cfoutput>

2. Dynamic Key Retrieval

anyEmployee = model("employee").findByKey(params.key);

primaryKey = anyEmployee.key();
writeOutput("Primary key value is: " & primaryKey);

3. Composite Primary Key

subscription = model("subscription").findByKey(customerId=3, publicationId=7);

<cfoutput>
Composite Keys: #subscription.key()# <!--- Outputs: "3,7" --->
</cfoutput>

4. Use in Links or Forms
<cfset employee = model("employee").findByKey(42)>

<!--- Generate a link with dynamic primary key --->
<a href="#linkTo(action='edit', id=employee.key())#">Edit Employee</a>

<!--- Hidden field for a form --->
#hiddenField(objectName="employee", property="id")#

5. Passing Keys in Nested Relationships
<!--- Suppose a `bookAuthors` association exists --->
book = model("book").findByKey(15);

<cfloop array="#book.bookAuthors#" index="author">
    <cfoutput>
        Author Key: #author.key()# <br>
    </cfoutput>
</cfloop>