Skip to content

Miscellaneous

hasMany()

hasMany() — returns any

Sets up a hasMany association between this model and the specified one.

NameTypeRequiredDefaultDescription
namestringyesGives the association a name that you refer to when working with the association (in the include argument to findAll, to name one example).
modelNamestringyesName of associated model (usually not needed if you follow CFWheels conventions because the model name will be deduced from the name argument).
foreignKeystringyesForeign key property name (usually not needed if you follow CFWheels conventions since the foreign key name will be deduced from the name argument).
joinKeystringyesColumn name to join to if not the primary key (usually not needed if you follow wheels conventions since the join key will be the tables primary key/keys).
joinTypestringyesouterUse to set the join type when joining associated tables. Possible values are inner (for INNER JOIN) and outer (for LEFT OUTER JOIN).
dependentstringyesfalseDefines how to handle dependent models when you delete a record from this model. Set to delete to instantiate associated models and call their delete method, deleteAll to delete without instantiating, removeAll to remove the foreign key, or false to do nothing.
shortcutstringyesSet this argument to create an additional dynamic method that gets the object(s) from the other side of a many-to-many association.
throughstringyesSet this argument if you need to override CFWheels conventions when using the shortcut argument. Accepts a list of two association names representing the chain from the opposite side of the many-to-many relationship to this model.
// Specify that instances of this model has many comments (the table for the associated model, not the current, should have the foreign key set on it).
hasMany("comments");

// Specify that this model (let''s call it `reader` in this case) has many subscriptions and setup a shortcut to the `publication` model (useful when dealing with many-to-many relationships).
hasMany(name="subscriptions", shortcut="publications");

// Automatically delete all associated `comments` whenever this object is deleted
hasMany(name="comments", dependent="deleteAll");

// When not following CFWheels naming conventions for associations, it can get complex to define how a `shortcut` works.
// In this example, we are naming our `shortcut` differently than the actual model''s name.

// In the models/Customer.cfc `init()` method
hasMany(name="subscriptions", shortcut="magazines", through="publication,subscriptions");

// In the models/Subscription.cfc `init()` method
belongsTo("customer");
belongsTo("publication");

// In the models/Publication `init()` method
hasMany("subscriptions");