I'm trying to set up a relationship between two tables, articles and categories. It is a 1-to-1 relationship where articles.category_id = categories.id
. I have the following set up.
controllers/home.cfc
<cfcomponent extends="Controller">
<cffunction name="index">
<cfset qFeaturedArticles = model("articles").findAll(
where="show_homepage = 1",
include="categories",
order="homepage_order"
) />
</cffunction>
</cfcomponent>
model/categories.cfc
<cfcomponent extends="Model">
<cffunction name="init">
<cfset hasOne("articles", foreignKey="category_id") />
</cffunction>
</cfcomponent>
model/articles.cfc
<cfcomponent extends="Model">
<cffunction name="init">
<cfset belongsTo("categories", dependent="nullify") />
</cffunction>
</cfcomponent>
This is the error I am getting.
Invalid CFML construct found on line 4 at column 49.ColdFusion was looking at the following text: = The CFML compiler was processing:
The specific sequence of files included or processed is: \cfusion\wwwroot\foo\index.cfm, line: 4
First of all I would like to point to categories.cfc model. If you are specifying hasOne
relationship then in that case the code should look like as follows:
<cfset hasOne("article", foreignKey="category_id") />
Note that instead of articles
you need to put article
in case of hasOne
.
But, literally speaking, the relation between categories and articles should be one to many
. I mean a category can have many articles.
So the categories.cfc should be written as follows:
<cfcomponent extends="Model">
<cffunction name="init">
<cfset hasMany("articles", foreignKey="category_id") />
</cffunction>